在 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?
}
由于该文件充当占位符,因此无法删除该文件。
Use 文件通道.截断 https://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html#truncate-long-:
try (FileChannel outChan = new FileOutputStream(f, true).getChannel()) {
outChan.truncate(newSize);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)