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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31800816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:09:21  来源:igfitidea点击:

How to check if file content is empty

javafilehadoopmapreducebufferedreader

提问by Unmesha SreeVeni

I am trying to check if a file content is empty or not. I have a source file where the content is empty. I tried different alternatives.But nothing is working for me.

我正在尝试检查文件内容是否为空。我有一个内容为空的源文件。我尝试了不同的选择。但没有什么对我有用。

Here is my code:

这是我的代码:

  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();

    }

I have tried using -

我试过使用 -

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

All of the above is giving as not empty.And I need to use -

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

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

Instead of new File() etc.

而不是 new File() 等。

Please advice if I went wrong somewhere.

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

EDIT

编辑

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

再清楚一点。如果我有一个只有空格或没有空格的文件,我希望我的结果为空。

回答by Elliott Frisch

You could call File.length()(which Returns the length of the file denoted by this abstract pathname) and check that it isn't 0. Something like

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

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

    }
}

To ignore white-space (as also being empty)

忽略空白(也为

You could use Files.readAllLines(Path)and something like

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

回答by Barnash

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

Of course you will need to close the isand catch IOException

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

回答by Sarath Kumar Sivan

You can try something like this:

你可以尝试这样的事情:

A Utility class to handle the isEmptyFile check

用于处理 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);
    }

}

Class to test the Utility

测试实用程序的类

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();
        }
    }

}