无法使用BufferedWriter将数据附加到文件

时间:2013-09-29 16:25:08

标签: java bufferedwriter

这是重写整个文件。如何将内容附加到现有文件“Data.txt”?

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class WriteToFile {
    public static void main(String[] args) 
    {
        try 
        {
            String content = "This is the content to write into file";
            BufferedWriter bw = new BufferedWriter(new FileWriter("Data.txt", true));
            bw.append(content);
            System.out.println("Done");
            bw.close();
        } catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

虽然,你的代码对我有用。你可以测试另一种方式。使用BufferedWriter包裹您的PrintWriter并运行。

 String content = "This is the content to write into file";
 PrintWriter out =new PrintWriter(new BufferedWriter(new FileWriter("Data.txt", true)));
 out.append(content);
 out.close();