Java,写入带有标题的文件

Java, write to file with headings

我有这个方法,需要一个 String 并将其写入文件。我将 PrintWriter 设置为 true 因为我想保存所有写入它的数据。

我想在这个文件上加上标题。如何将标题写入文件并且只写入一次?

我的方法是这样的:

public static void writeToFile(String text) {

    try {
        File f = new File("test.txt");
        FileWriter writer = new FileWriter("test", true); 
        writer.write(text);


        writer.close();
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
}

你可以用BufferWriter写一句话,看看更好的文件处理方式

try {

        String content = "This is the content to write into file";

        File f = new File("test.txt");

        // if file doesnt exists, then create it
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        bw.close();

        System.out.println("Done");

    } catch (IOException e) {
        e.printStackTrace();
    }finally{
    writer.close();
}
}

不清楚您的文件是否有多个标题。假设您的文件只有一个标题,我们可以按如下方式进行 -

1. 由于您的文件只包含一次标题,您可以检查文件是否是第一次访问 -

File f = new File(//your file name);
if(f.exists() && !f.isDirectory()) {
  //write heading
}  

2. 如果文件是第一次访问那么你可以添加一个 header -

String heading = "Some heading";

完整代码如下 -

public static void writeToFile(String text) {

    String heading = "Some heading";

    try {
        File f = new File("test.txt");
        FileWriter writer = new FileWriter(f, true); 

        if(f.exists() && !f.isDirectory()) {
          writer.write(heading);
       } 

        writer.write(text);

    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }finally{
        writer.close();
    }
}