在Java中截断文件的最佳实践方式是什么?例如这个虚拟函数,只是作为一个例子来阐明的意图:因为文件被用作占位Java中的文件截断操作
void readAndTruncate(File f, List<String> lines)
throws FileNotFoundException {
for (Scanner s = new Scanner(f); s.hasNextLine(); lines.add(s.nextLine())) {}
// truncate f here! how?
}
的文件无法删除。
我最终做了简单的'try {new FileOutputStream(f).getChannel()。truncate(0).close(); } catch(IOException e){/ * log and ignore * /}'。问题:如果使用append == true打开文件,它是否重要? – hyde
然后只是'新的FileWriter(f).close()'。 –
如果你打开时没有追加=='true',那么文件立即被截断(你想要)。 –