Java Is Text File isTextFile(File f, int length)

Here you can find the source of isTextFile(File f, int length)

Description

is Text File

License

Open Source License

Declaration

public static boolean isTextFile(File f, int length) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
 * Distributed under license by Red Hat, Inc. All rights reserved.
 * This program is made available under the terms of the
 * Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/* w  w  w . jav  a 2s  . c  om*/
 *     Exadel, Inc. and Red Hat, Inc. - initial API and implementation
 ******************************************************************************/

import java.io.BufferedReader;
import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class Main {
    public static boolean isTextFile(File f, int length) {
        if (!f.isFile())
            return false;
        BufferedReader br = null;
        try {
            FileReader fr = new FileReader(f);
            br = new BufferedReader(fr);
            int l = (int) f.length();
            if (l > length)
                l = length;
            char[] cs = new char[l];
            br.read(cs, 0, l);
            br.close();
            fr.close();
            return isText(new String(cs));
        } catch (IOException e) {
            return false;
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    }

    public static boolean isText(String body) {
        if (body == null)
            return false;
        int l = body.length();
        for (int i = 0; i < l; i++) {
            char c = body.charAt(i);
            if (((int) c) < 32 && c != '\n' && c != '\r' && c != 't')
                return false;
        }
        return true;
    }
}

Related

  1. isText(File file)
  2. isText(File file)
  3. isTextFile(File f)
  4. isTextFile(File file)
  5. isTextFile(File file)