hyd*_*yde 15 java file-io file
在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?
}
Run Code Online (Sandbox Code Playgroud)
由于文件充当占位符,因此无法删除该文件.
Mor*_*sen 34
try (FileChannel outChan = new FileOutputStream(f, true).getChannel()) {
outChan.truncate(newSize);
}
Run Code Online (Sandbox Code Playgroud)
使用一个衬垫Files.write() ...
Files.write(outFile, new byte[0], StandardOpenOption.TRUNCATE_EXISTING);
Run Code Online (Sandbox Code Playgroud)
也可以使用File.toPath()事先从File转换为Path。
还允许其他StandardOpenOptions。