4

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.

USB
  • 6,019
  • 15
  • 62
  • 93
  • Related: http://stackoverflow.com/questions/7190618/most-efficient-way-to-check-if-a-file-is-empty-in-java-on-windows – UnknownOctopus Aug 04 '15 at 04:41
  • @UnknownOctopus: Yes I checked that too. But it is not working . I have to use new BufferedReader(new InputStreamReader(fs.open(in))); also . I dont want to use new File() – USB Aug 04 '15 at 04:45
  • What is the output of `System.out.println(">" + br.readline() + "<");`? – Sleafar Aug 04 '15 at 04:49
  • @Sleafar : Output : not empty >null< using the above mentioned code( if (br.readLine().length() == 0) {) – USB Aug 04 '15 at 04:52
  • Why don't you want to use `new File()`? reading the file is much more expensive than just looking at it with `new File()` – Barnash Aug 04 '15 at 04:53
  • @Barnash: This is a code snippet from my mapreduce job, In mapreduce new File wont work as we expect – USB Aug 04 '15 at 04:54
  • @UnmeshaSreeVeni ok, well, Writing a different answer – Barnash Aug 04 '15 at 05:00
  • @UnmeshaSreeVeni Then checking for `null` should have worked, odd. – Sleafar Aug 04 '15 at 05:05
  • @Sleafar : No that too didnt worked. I was also expecting the same,My tought was it will work.Once tested it is not working – USB Aug 04 '15 at 05:07

3 Answers3

9

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;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • even tough my file is empty.It is showing there is content using all of these code.I am still wondering – USB Aug 04 '15 at 11:59
  • Is empty length of 0 bytes, or is white space also "empty'? – Elliott Frisch Aug 04 '15 at 13:50
  • even if my file contains just whitespaces or 0 bytes it should show file is empty. My file contains white space – USB Aug 05 '15 at 08:59
  • Edit your question to include that little detail. Be aware you may have to read the entire file to determine emptiness with that definition. A million spaces is empty, a million spaces followed by a letter 'a' isn't. – Elliott Frisch Aug 05 '15 at 23:59
1
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 is and catch IOException

Barnash
  • 2,012
  • 3
  • 19
  • 22
  • That should not happen. Since the first read should return the first byte value in the file (which will be values from 0 to 255), if it returns -1 it means the read has ended – Barnash Aug 04 '15 at 05:42
  • is.read is returning an integer. and I included them in if else. could you please edit your answer by including if else – USB Aug 04 '15 at 05:52
  • Yes with the same code I am getting it as not empty.It is not working for me – USB Aug 04 '15 at 09:12
0

You can try something like this:

A Utility class to handle the isEmptyFile check

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

}
1218985
  • 7,531
  • 2
  • 25
  • 31
  • If my file is empty,It is not showing file empty.and If I am having white spaces in file then ,It is showing file is empty – USB Sep 16 '15 at 06:09