Java Is Text File isText(File file)

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

Description

Checks for text file.

License

Open Source License

Parameter

Parameter Description
file the file to check. Caller has to make sure that file exists.

Exception

Parameter Description
IOException if IOException occurs

Return

true if it is binary else false

Declaration

public static boolean isText(File file) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2014 Ericsson//from w w  w  .  j  a  va2  s.c o  m
 *
 * All rights reserved. This program and the accompanying materials are
 * 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:
 *   Alexandre Montplaisir - Initial API and implementation
 *******************************************************************************/

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Main {
    private static final int MAX_NB_BINARY_BYTES = 2048;

    /**
     * Checks for text file.
     *
     * Note that it checks for binary value 0 in the first MAX_NB_BINARY_BYTES
     * bytes to determine if the file is text.
     *
     * @param file
     *            the file to check. Caller has to make sure that file exists.
     * @return true if it is binary else false
     * @throws IOException
     *             if IOException occurs
     * @since 1.2
     */
    public static boolean isText(File file) throws IOException {
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) {
            int count = 0;
            int val = bufferedInputStream.read();
            while ((count < MAX_NB_BINARY_BYTES) && (val >= 0)) {
                if (val == 0) {
                    return false;
                }
                count++;
                val = bufferedInputStream.read();
            }
        }
        return true;
    }
}

Related

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