File truncate operation in Java

file, file-io, java

Solution

Use FileChannel.truncate:

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

Problem

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.

Original source