这是重写整个文件。如何将内容附加到现有文件“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();
}
}
}
答案 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();