Truncate a File in Java



The flush() method of the FileWriter class flushes the contents of the file. You can use this method to truncate a file.

Example

import java.io.File;
import java.io.FileWriter;

public class FileTruncate {
   public static void main(String args[]) throws Exception {
      File file = new File("myData");
      FileWriter fw = new FileWriter(file, false);
      fw.flush();
      System.out.println("File truncated");
   }
}

Output

File truncated
Updated on: 2020-02-20T09:55:21+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements