Java Is Text File isText(File file)

Here you can find the source of isText(File file)

Description

is Text

License

Open Source License

Declaration

public static boolean isText(File file) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;

public class Main {
    public static boolean isText(File file) {
        try {/*  ww w.  ja  va 2s . co m*/
            // Get first 512 bytes of file
            byte[] buf = new byte[512];
            FileInputStream in = new FileInputStream(file);
            int len = in.read(buf);
            in.close();

            // Empty files are considered text
            if (len == 0)
                return true;

            int numNonTextChars = 0;
            for (int i = 0; i < len; i++) {
                // Files with null bytes are likely binary
                if (buf[i] == 0)
                    return false;

                // Count non-text characters
                if (buf[i] < 32 || buf[i] >= 127)
                    numNonTextChars++;
            }
            // Filse with less than 30% non-text characters are considered text
            return numNonTextChars / (double) len < 0.30;
        } catch (IOException e) {
            return false;
        }
    }
}

Related

  1. isText(File file)
  2. isTextFile(File f)
  3. isTextFile(File f, int length)
  4. isTextFile(File file)