Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if file content is empty

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.

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.

like image 701
Unmesha Sreeveni U.B Avatar asked Jan 08 '23 20:01

Unmesha Sreeveni U.B


1 Answers

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 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

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;
}
like image 56
Elliott Frisch Avatar answered Jan 10 '23 22:01

Elliott Frisch