我想在java中用单个文件编写,但是用不同的方法编写。我写了这个
import java.io.*;
public class Test {
public static File file = new File("text.log");
public static void main (String [] args) throws IOException
{
FileWriter input= new FileWriter(file);
input.write("hello");
input.write("\n");
input.close();
test();
}
public static void test() throws IOException
{
FileWriter input= new FileWriter(file);
input.write("world");
input.write("\n");
input.close();
}
}
输出只是world
。看起来调用函数test()
会覆盖以前写的内容。
答案 0 :(得分:3)
您需要通过传递FileWriter
作为第二个参数来打开附加模式中的true
:
public static File file = new File("text.log", true);
来自Javadoc:
public FileWriter(String fileName,boolean append)
给定File对象的构造FileWriter对象。如果第二个参数为true,则字节将写入文件的末尾而不是开头。
答案 1 :(得分:1)
当你写new FileWriter(file, true)
时,它会附加而不是覆盖。