【发布时间】:2014-12-17 16:59:12
【问题描述】:
我在尝试追加到现有文本文件时遇到了一些问题。
它似乎没有附加一行文本。到目前为止,我已经有了这个方法:
public static void addLine(File f, String line) {
try {
FileWriter fw = new FileWriter(f.getName(), true);
BufferedWriter buffer = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(buffer);
pw.println(line);
pw.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
我主要有以下几点:
public static void main(String[] args) {
File f = new File("adresOfFile");
if (f.exists() && !f.isDirectory()) {
System.out.println("File " + f.getName() + " exists!");
System.out.println("\n" + "Path: " + f.getAbsolutePath());
System.out.println("\n" + "Parent: " + f.getParent());
System.out.println("\n" + "--------------CONTENT OF FILE-------------");
addLine(f, "");
addLine(f, "The line to append");
try {
displayContent(f);
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("File not found");
}
}
当我运行程序时,它似乎没有给出任何错误。运行程序应该打印出现有文本(displayContent),这是在附加(addLine)之后完成的。但是当我运行它时,它只显示现有文本,没有附加行。
它也不显示在文本文件中。我试图放一个 System.out.println();在方法中,它会打印出来,所以我知道它正确地运行了方法,只是没有附加。
EDIT AWNSER:将 f.getName() 替换为 f,并在 pw.close() 之前添加 pw.flush
【问题讨论】:
标签: java file text append printwriter