What is the method in Java to empty the contents of a file?

In Java, there are multiple ways to clear the contents of a file, here are some commonly used methods:

  1. Use the FileWriter class to write over existing content:
File file = new File("example.txt");
try (FileWriter writer = new FileWriter(file)) {
    writer.write(""); // 将文件内容设置为空字符串
} catch (IOException e) {
    e.printStackTrace();
}
  1. Perform an overwrite writing using the PrintWriter class.
File file = new File("example.txt");
try (PrintWriter writer = new PrintWriter(file)) {
    writer.print(""); // 将文件内容设置为空字符串
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
  1. Perform overwrite writing using the RandomAccessFile class.
File file = new File("example.txt");
try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
    raf.setLength(0); // 设置文件长度为0,即清空文件内容
} catch (IOException e) {
    e.printStackTrace();
}

These are several commonly used methods, you can choose the appropriate method to clear the content of the file according to your own needs.

bannerAds