【问题标题】:Java - is there a way to open a text file if it does not exist already, and append to it if it does exist?Java - 如果文本文件不存在,有没有办法打开它,如果它确实存在则附加到它?
【发布时间】:2018-07-29 07:55:48
【问题描述】:

我对 Java 很陌生,我遇到了这个问题。如果 java 代码不存在,我希望它创建一个 txt 文件,但如果存在,我希望 PrintWriter 使用 FileWriter 附加到它。这是我的代码:

编辑:我试图修复我的代码,但现在我收到了 IOException 错误。我在这里做错了什么? 编辑2:我认为我的代码是独一无二的,因为我试图让它在文件不存在时创建一个新文件,如果它已经存在则让它附加到现有文件。

import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

/**
 * Created by FakeOwl96 on 3/28/2017.
 */
public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.nextLine();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}

【问题讨论】:

  • 谢谢,但我不这么认为,因为我试图让代码创建 txt 文件,如果它不存在的话。
  • 链接的问题提供了很多答案,还包含丢失文件的创建。如果你仔细观察,你会发现,这个问题的很多答案与链接问题的答案相同。这就是为什么我建议这个问题可能重复。
  • 啊,明白了。我会仔细看看。我确实有点浏览了它们,哈哈

标签: java


【解决方案1】:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class AreaOfCircle {
    private static double PI = Math.PI;
    private double radius;
    private static double area;
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        AreaOfCircle a = new AreaOfCircle();
        System.out.print("Type in the radius of circle: ");
        a.radius = keyboard.nextDouble();
        getArea(a.radius);
        System.out.print("Name of the txt file you want to create:");
        String fileName = keyboard.next();
        keyboard.nextLine();
        try {
            File myFile = new File(fileName);
            if (!myFile.exists()) {
                myFile.createNewFile();
            }
            FileWriter fw = new FileWriter(myFile, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("The area of the circle is " + area + ".\n");
            bw.close();
        }
        catch (IOException e) {
            System.out.println("IOException Occured");
            e.printStackTrace();
        }
    }

    public static void getArea(double n) {
        area = n * PI;
    }
}

我所做的唯一改变是 字符串文件名 = 键盘.next();来自 //keyboard.nextLine() 上面的代码对我有用。希望这会有所帮助。

【讨论】:

  • 谢谢。将 keyboard.nextLine() 更改为 keyboard.next() 后,它也对我有用。能否简要解释一下为什么 nextLine() 会触发 IOException?
  • nextLine() 将此扫描器前进到当前行并返回被跳过的输入。 docs.oracle.com/javase/8/docs/api/java/util/… 使用keyboard.nextLine() 使fileName 为空,因此它尝试创建一个空文件 if (!myFile.exists()) {myFile.createNewFile();} 导致IOException。
  • @FakeOwl96 您还有其他问题吗?如果您对我的解释感到满意,您介意接受我的回答吗?
  • 我完全忘了 xD 我会的!
【解决方案2】:

在初始化myFile后添加以下行:

myFile.createNewFile(); // if file already exists will do nothing

【讨论】:

    【解决方案3】:

    这是文件追加行的另一个示例,如果文件不存在则创建新文件。

    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    public class AppendFileDemo2 {
    
        public static void main(String[] args) {
            try {
                File file = new File("myfile2.txt");
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileWriter fw = new FileWriter(file, true);
                BufferedWriter bw = new BufferedWriter(fw);
                PrintWriter pw = new PrintWriter(bw);
                //This will add a new line to the file content
                pw.println("");
                /* Below three statements would add three 
               * mentioned Strings to the file in new lines.
                 */
                pw.println("This is first line");
                pw.println("This is the second line");
                pw.println("This is third line");
                pw.close();
    
                System.out.println("Data successfully appended at the end of file");
    
            } catch (IOException ioe) {
                System.out.println("Exception occurred:");
                ioe.printStackTrace();
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      这是文件追加行的示例,如果文件不存在则创建新文件。

      import java.io.BufferedWriter;
      import java.io.File;
      import java.io.FileWriter;
      import java.io.IOException;
      public class AppendFileDemo {
      
          public static void main(String[] args) {
              try {
                  String content = "This is my content which would be appended "
                          + "at the end of the specified file";
                  //Specify the file name and path here
                  File file = new File("myfile.txt");
      
                  /* This logic is to create the file if the
               * file is not already present
                   */
                  if (!file.exists()) {
                      file.createNewFile();
                  }
      
                  //Here true is to append the content to file
                  FileWriter fw = new FileWriter(file, true);
                  //BufferedWriter writer give better performance
                  BufferedWriter bw = new BufferedWriter(fw);
                  bw.write(content);
                  //Closing BufferedWriter Stream
                  bw.close();
      
                  System.out.println("Data successfully appended at the end of file");
      
              } catch (IOException ioe) {
                  System.out.println("Exception occurred:");
                  ioe.printStackTrace();
              }
          }
      }
      

      【讨论】:

      • 非常感谢!顺便说一句,BufferedWriter 比 PrintWriter 更好是有原因的吗?我应该开始使用 BufferedWriter 而不是一直使用 PrintWriter 吗?
      • 另外,我尝试通过您的解决方案修复我的代码,现在我得到了 IOException。我做错了什么?
      【解决方案5】:

      还有一个例子,这次使用try-with-resources 并使用Files class 创建BufferedWriter

      public void write(File file, String text) throws IOException {
          Path path = file.toPath();
          Charset charSet = StandardCharsets.UTF_8;
          OpenOption[] options = new OpenOption[]{
              StandardOpenOption.CREATE, // Create a new file if it does not exist
              StandardOpenOption.WRITE,  // Open for write access
              StandardOpenOption.APPEND  // Bytes will be written to the end of
                                         // the file rather than the beginning
          };
          try (BufferedWriter bw = Files.newBufferedWriter(path, charSet, options)) {
              bw.write(text);
          }
      }
      

      以上示例可在 GitHub 上进行测试。

      您也可以使用Files.write 方法:

      public void write(File file, List<String> lines) throws IOException {
          Path path = file.toPath();
          Charset charSet = StandardCharsets.UTF_8;
          OpenOption[] options = new OpenOption[]{
              StandardOpenOption.CREATE, // Create a new file if it does not exist
              StandardOpenOption.WRITE,  // Open for write access
              StandardOpenOption.APPEND  // Bytes will be written to the end of
                                         // the file rather than the beginning
          };
          Files.write(path, lines, charSet, options);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-20
        • 2021-01-31
        • 1970-01-01
        • 1970-01-01
        • 2015-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多