2

我有一个代码应该在文件中写入行.. - 如果文件不存在,它应该使用该名称创建新文件。- 如果文件存在,它应该只写新行...

它似乎总是制作新文件,我不知道如何避免它......这是我的代码......

如果文件已经存在,如何让它只写新行?

谢谢你的时间...

if (isANumber(value) == true) {
    String valResult = "validation_result=VALID";
    BufferedWriter writer = null;
    writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("ValidationResults.txt")));
    System.out.println("Writing in TEXT file: " + "type=" + key + ";value=" +  value + ";" + valResult);
    writer.newLine();
    writer.write("\ntype=" + key + ";value=" +  value +  valResult + "\n");
    writer.flush();
    writer.close();
} else {
    valResult = "validation_result=INVALID";
    BufferedWriter writer =  new BufferedWriter(new OutputStreamWriter(new FileOutputStream("ValidationResults.txt")));
    System.out.println("Writing in TEXT file: " + "type=" + key + ";value=" +  value + ";" +  valResult);
    writer.newLine();
    writer.write("\ntype=" + key + ";value=" +  value + ";" + valResult + "\n");
    writer.flush();
    writer.close();
}
4

1 回答 1

2

使用 FileWriter。那应该可以解决你的问题。True 参数表示下一行将附加到现有文件。如果您使用 false 而不是该文件将被覆盖。

new BufferedWriter(new FileWriter("file.txt", true));
于 2013-07-04T10:33:10.077 回答