Java中的文件截断操作
在Java中截断文件的最佳实践方法是什么? 例如,这个虚拟函数,仅作为澄清意图的示例:
void readAndTruncate(File f, List 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); }
new FileWriter(f)
将在打开时截断文件(到零字节),之后你可以写入行
使用Files.write()的一个class轮…
Files.write(outFile, new byte[0], StandardOpenOption.TRUNCATE_EXISTING);
也可以使用File.toPath()从File转换为Path。
还允许其他StandardOpenOptions 。
这取决于你将如何写入文件,但最简单的方法是打开一个新的FileOutputStream,而不指定你计划附加到文件(注意:基础FileOuptutStream
构造函数将截断文件,但如果你想要明确该文件被截断,我建议使用双参数变体)。
使用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);