Alex Rivera | Logout

Determining binary/text file type in Java?

Asked 2009-03-07T00:31:04.477
53

Namely, how would you tell an archive (jar/rar/etc.) file from a textual (xml/txt, encoding-independent) one?

Edit
Report

2 Answers

14

I made this one. A bit simpler, but for latin-based languages, it should work fine, with the ratio adjustment.

/**
 *  Guess whether given file is binary. Just checks for anything under 0x09.
 */
public static boolean isBinaryFile(File f) throws FileNotFoundException, IOException {
    FileInputStream in = new FileInputStream(f);
    int size = in.available();
    if(size > 1024) size = 1024;
    byte[] data = new byte[size];
    in.read(data);
    in.close();

    int ascii = 0;
    int other = 0;

    for(int i = 0; i < data.length; i++) {
        byte b = data[i];
        if( b < 0x09 ) return true;

        if( b == 0x09 || b == 0x0A || b == 0x0C || b == 0x0D ) ascii++;
        else if( b >= 0x20  &&  b <= 0x7E ) ascii++;
        else other++;
    }

    if( other == 0 ) return false;

    return 100 * other / (ascii + other) > 95;
}
answered 2012-11-23T17:16:05.293
11

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

answered 2009-10-21T06:39:18.130

Your Answer