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

4
我将尝试检查文件内容是否为空。我有一个源文件,其中内容为空。我尝试了不同的替代方案,但是都没有起作用。
以下是我的代码:
  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()等方法。

请指导我是否有错误之处。

编辑

更清晰地表达一下。如果我有一个只有空格或没有空格的文件,我希望我的结果是空的。


相关链接:https://dev59.com/oGw05IYBdhLWcg3whCJn - UnknownOctopus
System.out.println(">" + br.readline() + "<"); 的输出是什么? - Sleafar
为什么你不想使用 new File()?读取文件比使用 new File() 查看文件要昂贵得多。 - Barnash
@Barnash:这是我MapReduce作业中的代码片段,在MapReduce中,新文件不会像我们预期的那样起作用。 - USB
@Sleafar:不,那个也没用。我也期望它能行,我的想法是它会行的。一旦测试过了,发现它并不起作用。 - USB
显示剩余4条评论
3个回答

9
你可以调用 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;
}

您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - USB
空的长度为0字节,或者空格也算“空”吗? - Elliott Frisch
即使我的文件只包含空格或0字节,它也应该显示文件为空。我的文件包含空格。 - USB
编辑您的问题以包含那个小细节。请注意,您可能需要阅读整个文件才能确定根据该定义是否为空。一百万个空格是空的,一百万个空格后跟一个字母'a'则不是空的。 - Elliott Frisch

1
InputStream is = new FileInputStream("myfile.txt");
if (is.read() == -1) {
    // The file is empty!
} else {
    // The file is NOT empty!
}

当然,你需要关闭 is 并捕获 IOException

这不应该发生。由于第一次读取应返回文件中的第一个字节值(将是从0到255的值),如果返回-1,则表示读取已结束。 - Barnash
is.read 返回一个整数。我已经将它们包含在 if else 中。你能否编辑你的答案,包括 if else? - USB
是的,使用相同的代码我得到的结果不为空。但它对我来说不起作用。 - USB

0
你可以尝试这样做: 一个实用类来处理isEmptyFile检查
package com.stackoverflow.answers.mapreduce;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class HDFSOperations {

    private HDFSOperations() {}

    public static boolean isEmptyFile(Configuration configuration, Path filePath)
            throws IOException {
        FileSystem fileSystem = FileSystem.get(configuration);
        if (hasNoLength(fileSystem, filePath))
            return false;
        return isEmptyFile(fileSystem, filePath);
    }

    public static boolean isEmptyFile(FileSystem fileSystem, Path filePath)
            throws IOException {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(fileSystem.open(filePath)));
        String line = bufferedReader.readLine();
        while (line != null) {
            if (isNotWhitespace(line))
                return false;
            line = bufferedReader.readLine();
        }
        return true;
    }

    public static boolean hasNoLength(FileSystem fileSystem, Path filePath)
            throws IOException {
        return fileSystem.getFileStatus(filePath).getLen() == 0;
    }

    public static boolean isWhitespace(String str) {
        if (str == null) {
            return false;
        }
        int length = str.length();
        for (int i = 0; i < length; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    public static boolean isNotWhitespace(String str) {
        return !isWhitespace(str);
    }

}

用于测试实用工具的类

package com.stackoverflow.answers.mapreduce;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;

public class HDFSOperationsTest {

    public static void main(String[] args) {
        String fileName = "D:/tmp/source/expected.txt";
        try {
            Configuration configuration = new Configuration();
            Path filePath = new Path(fileName);
            System.out.println("isEmptyFile: "
                    + HDFSOperations.isEmptyFile(configuration, filePath));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

}

如果我的文件是空的,它不会显示为空;但如果文件中有空格,则会显示为空。 - USB

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接