Java中的文件截断操作 [英] File truncate operation in Java
本文介绍了Java中的文件截断操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Java 中截断文件的最佳实践方法是什么?比如这个dummy函数,只是为了说明意图:
What is the best-practice way to truncate a file in Java? For example this dummy function, just as an example to clarify the intent:
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?
}
无法删除该文件,因为该文件用作占位符.
The file can not be deleted since the file is acting as a place holder.
推荐答案
try (FileChannel outChan = new FileOutputStream(f, true).getChannel()) {
outChan.truncate(newSize);
}
这篇关于Java中的文件截断操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文