22

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

}

由于该文件充当占位符,因此无法删除该文件。

4

7 回答 7

38

使用FileChannel.truncate

try (FileChannel outChan = new FileOutputStream(f, true).getChannel()) {
  outChan.truncate(newSize);
}
于 2013-01-11T14:44:33.150 回答
12

一个使用Files.write()的班轮...

Files.write(outFile, new byte[0], StandardOpenOption.TRUNCATE_EXISTING);

也可以使用File.toPath()从 File 转换为 Path 之前。

还允许其他StandardOpenOptions

于 2016-03-30T17:54:07.063 回答
8

new FileWriter(f)将在打开时截断您的文件(为零字节),之后您可以向其写入行

于 2013-01-11T14:48:07.810 回答
3

这取决于您将如何写入文件,但最简单的方法是打开一个新的FileOutputStream而不指定您打算追加到文件(注意:基本FileOuptutStream构造函数将截断文件,但如果您想明确文件被截断,我建议使用双参数变体)。

于 2013-01-11T14:42:42.360 回答
1

RandomAccessFile.setLength() seems to be exactly what's prescribed in this case.

于 2020-04-15T18:57:45.637 回答
0

使用RandomAccessFile#read并将以这种方式记录的字节推送到新File对象中。

RandomAccessFile raf = new RandomAccessFile(myFile,myMode);  
byte[] numberOfBytesToRead = new byte[truncatedFileSizeInBytes];  
raf.read(numberOfBytesToRead);    
FileOutputStream fos = new FileOutputStream(newFile);  
fos.write(numberOfBytesToRead);
于 2013-01-11T14:41:55.160 回答
0

使用 Apache Commons IO API:

    org.apache.commons.io.FileUtils.write(new File(...), "", Charset.defaultCharset());
于 2020-04-26T20:06:23.040 回答