【问题标题】:Java, write to file with headingsJava,写入带有标题的文件
【发布时间】:2015-05-03 05:43:13
【问题描述】:

我有这种方法,它需要一个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());
    }
}

【问题讨论】:

  • 很抱歉。我的意思是头条新闻。
  • 很抱歉我不懂DYM。我只需要在文件顶部打印名称、nuber、日期等简单文本,然后在下面打印我的数据。

标签: java file writetofile


【解决方案1】:

不清楚您的文件是否有多个标题。假设您的文件只有一个标题,我们可以这样做 -

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

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

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

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();
    }
}

【讨论】:

  • 完整代码对吗?它在打开文件进行写入后检查文件是否存在,所以我想你会发现它总是存在的。我错了吗?
【解决方案2】:

你可以用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();
}
}

【讨论】:

  • 请编辑,以便“尝试”被格式化。您应该像 Razib 一样关闭文件,这样无论是否有异常,它都会关闭。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
  • 2014-11-23
  • 2019-08-23
  • 1970-01-01
  • 2016-04-18
相关资源
最近更新 更多