温馨提示×

Java判断文件内容为空的方法是什么

小亿
97
2023-12-21 10:01:17
栏目: 编程语言

在Java中,可以使用以下方法判断文件内容是否为空:

  1. 使用File类的length()方法:该方法返回文件的大小,如果文件大小为0,则可以判断文件内容为空。
import java.io.File;

public class FileIsEmptyExample {
    public static void main(String[] args) {
        File file = new File("path/to/file.txt");
        if (file.length() == 0) {
            System.out.println("文件内容为空");
        } else {
            System.out.println("文件内容不为空");
        }
    }
}
  1. 使用BufferedReader类读取文件内容并判断是否为空:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileIsEmptyExample {
    public static void main(String[] args) {
        File file = new File("path/to/file.txt");

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            if (reader.readLine() == null) {
                System.out.println("文件内容为空");
            } else {
                System.out.println("文件内容不为空");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这两种方法都可以判断文件内容是否为空,可以根据具体的需求选择使用哪种方法。

0