java - 如何检查文件内容是否为空

标签 java file hadoop mapreduce bufferedreader

我正在尝试检查文件内容是否为空。我有一个内容为空的源文件。 我尝试了不同的替代方法。但没有任何方法适合我。

这是我的代码:

  Path in = new Path(source);
    /*
     * Check if source is empty
     */
    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(fs.open(in)));
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        if (br.readLine().length() == 0) {
            /*
             * Empty file
             */
            System.out.println("In empty");
            System.exit(0);

        }
        else{
            System.out.println("not empty");
        }
    } catch (IOException e) {
        e.printStackTrace();

    }

我试过使用 -

1. br.readLine().length() == 0
2. br.readLine() == null
3. br.readLine().isEmpty()

以上所有内容都不是空的。我需要使用 -

BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(fs.open(in)));
        } catch (IOException e) {
            e.printStackTrace();
        }

代替 new File() 等

如果我哪里出错了,请指教。

编辑

Making little more clear. If I have a file with just whitespaces or without white space,I am expecting my result as empty.

最佳答案

您可以调用 File.length() (返回此抽象路径名表示的文件的长度)并检查它是否不是 0。有点像

File f = new File(source);
if (f.isFile()) {
    long size = f.length();
    if (size != 0) {

    }
}

忽略空白(因为也是)

你可以使用 Files.readAllLines(Path)和类似的东西

static boolean isEmptyFile(String source) {
    try {
        for (String line : Files.readAllLines(Paths.get(source))) {
            if (line != null && !line.trim().isEmpty()) {
                return false;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Default to true.
    return true;
}

关于java - 如何检查文件内容是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31800816/

相关文章:

Android:将文件保存到 SD 卡?

java - 如何在 Hadoop Mapreduce 中使用 MultithreadedMapper 类?

java - 在两个链接表(通过 fk 链接)的第二个表中创建行不起作用

java - 在 Azure VM 上使用 NGINX 对其他 Azure VM 进行负载平衡

Java - 如何将文件写入指定目录

java - jdk src 文件无法解压

hadoop - hadoop 中的数据存储复制与云中的雪花

hadoop - 是否可以在docker文件中间执行CMD?

java - 使用 JNLP API 获取 .jnlp 文件内资源下的 JAR

java - 为什么 String.equals() 不在后台使用 hashCode() 相等性检查?