Determining binary/text file type in Java? Determining binary/text file type in Java? java java

Determining binary/text file type in Java?


There's no guaranteed way, but here are a couple of possibilities:

  1. Look for a header on the file. Unfortunately, headers are file-specific, so while you might be able to find out that it's a RAR file, you won't get the more generic answer of whether it's text or binary.

  2. Count the number of character vs. non-character types. Text files will be mostly alphabetical characters while binary files - especially compressed ones like rar, zip, and such - will tend to have bytes more evenly represented.

  3. Look for a regularly repeating pattern of newlines.


Using Java 7 Files class http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType(java.nio.file.Path)

boolean isBinaryFile(File f) throws IOException {        String type = Files.probeContentType(f.toPath());        if (type == null) {            //type couldn't be determined, assume binary            return true;        } else if (type.startsWith("text")) {            return false;        } else {            //type isn't text            return true;        }    }


Run file -bi {filename}. If whatever it returns starts with 'text/', then it's non-binary, otherwise it is. ;-)