25

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.

0

7 Answers 7

42

Use FileChannel.truncate:

try (FileChannel outChan = new FileOutputStream(f, true).getChannel()) {
  outChan.truncate(newSize);
}
5
  • 2
    I ended up doing simple try { new FileOutputStream(f).getChannel().truncate(0).close(); } catch (IOException e) { /* log and ignore */ }. Question: does it matter if file is opened with append==true, or not?
    – hyde
    Jan 11, 2013 at 15:21
  • Then just new FileWriter(f).close(). Jan 11, 2013 at 16:05
  • 4
    If you open without append == true th file gets immediately truncated (wha you want). Jan 11, 2013 at 16:14
  • 1
    Just opening a FileOutputStream without using append == true will cause the file to be truncated (at least on openjdk on linux). So new FileOutputStream( path ).close(); will cause it to be truncated on my system. Apr 8, 2014 at 23:41
  • 3
    I prefer the FileChannel approach, as it does not rely on side effect when closing the output stream. Also a better option as it makes the code more maintainable: There is no confusion what should happen when calling channel.truncate(newSize). So many bugs hide under the heading of a series of unintentional consequences.
    – Andries
    Sep 21, 2014 at 9:56
15

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.

8

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

4

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).

2
  • Not going to write to the file, just want to truncate it to zero... It is read and processed, contents need to be cleared to avoid eating disk space, but file entry should remain.
    – hyde
    Jan 11, 2013 at 15:04
  • Yeah, FileOutputStream truncating makes sense, but I wonder why the docs don't mention it (they just say file will be written from beginning, without specifying what happens to previous file contents).
    – hyde
    Jan 11, 2013 at 15:06
2

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

0

Use RandomAccessFile#read and push the bytes recorded in this way into a new File object.

RandomAccessFile raf = new RandomAccessFile(myFile,myMode);  
byte[] numberOfBytesToRead = new byte[truncatedFileSizeInBytes];  
raf.read(numberOfBytesToRead);    
FileOutputStream fos = new FileOutputStream(newFile);  
fos.write(numberOfBytesToRead);
1
  • I think using RandomAccessFile would allow reading and then truncating with single file opening, so +1 for that.
    – hyde
    Jan 11, 2013 at 15:26
0

Use Apache Commons IO API:

    org.apache.commons.io.FileUtils.write(new File(...), "", Charset.defaultCharset());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.