File truncate operation in Java

It depends on how you're going to write to the file, but the simplest way is to open a new FileOutputStream without specifying that you plan to append to the file (note: the base FileOuptutStream constructor will truncate the file, but if you want to make it clear that the file's being truncated, I recommend using the two-parameter variant).


Use FileChannel.truncate:

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

new FileWriter(f) will truncate your file upon opening (to zero bytes), after that you can write lines to it


One liner using Files.write()...

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

Can use File.toPath() to convert from File to Path prior as well.

Also allows other StandardOpenOptions.

Tags:

Java

File

File Io