Java中如何删除一个文件的内容

529 阅读2分钟

学习使用标准的IO类和第三方库在不删除文件的情况下删除或清除文件的内容

1.使用PrintWriter构造函数

PrintWiter用于向文本输出流写入格式化的字符串。

PrintWriter(file) 构造函数用指定的文件参数创建一个新的PrintWriter如果文件存在,那么它将被截断为零大小;否则,将创建一个新文件。

File file = new File("/path/file");

try(PrintWriter pw = new PrintWriter(file)){
  //Any more operations if required
} catch (FileNotFoundException e) {
  e.printStackTrace();
}

2.使用FileWriter构造函数

FileWeite也被用来向字符文件写入文本。与PrintWriter类似,FileWriter的构造函数也在文件未被打开进行追加操作时清空文件

在给定的例子中,第二个参数false表示追加模式。如果它为,那么字节将被写到文件的末尾而不是开头。

File file = new File("/path/file");

try(FileWriter fw = new FileWriter(file)){
  //Any more operations if required
} catch (IOException e) {
  e.printStackTrace();
}

3.使用随机存取文件

一个随机访问文件的行为就像一个存储在文件系统中的大的字节数。我们可以使用它的*setLength()*方法来清空该文件。

try(RandomAccessFile raf = new RandomAccessFile(file, "rw")){
  raf.setLength(0);
} catch (FileNotFoundException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

4.使用NIO的Files.newBufferedWriter()

我们也可以使用BufferedWriter向文件中写入一个空字符串。这将通过删除其中的所有内容使文件的大小为零。

try(BufferedWriter writer = Files.newBufferedWriter(file.toPath())){
  	writer.write("");
	writer.flush();
} catch (IOException e) {
  e.printStackTrace();
}

5.使用Commons IO FileUtils

FileUtils类可以用来向文件中写入空字符串,这将有效地删除文件中的所有内容

File file = new File("/path/file");

try{
  FileUtils.write(file, "", StandardCharsets.UTF_8);
} catch (IOException e) {
  e.printStackTrace();
}

包括Maven中最新版本的Commons IO库。

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

6.结语

在这个Java教程中,我们学会了通过删除文件中的所有内容使文件变空。这使得文件的大小为零,而不会删除文件本身。

我们学会了使用Java IO的PrintWriterFileWriter、NIO的Files类和Commons IO的FileUtils类来清空文件。

学习愉快!!