gpt4 book ai didi

java - Java中的文件截断操作

转载 作者:太空狗 更新时间:2023-10-29 22:59:27 25 4
gpt4 key购买 nike

在 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?

}

无法删除该文件,因为该文件正在充当占位符。

最佳答案

使用FileChannel.truncate :

try (FileChannel outChan = new FileOutputStream(f, true).getChannel()) {
outChan.truncate(newSize);
}

关于java - Java中的文件截断操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14280385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com