集册 Java实例教程 检查文件是文本文件还是二进制文件。

检查文件是文本文件还是二进制文件。

欢马劈雪     最近更新时间:2020-07-07 04:41:02

808

检查文件是文本文件还是二进制文件。

Java 读取文件内容,我们经常用到,一般都是读取的是文本文件内容,二进制文件的内容无法读取。

计算机的文件基本上分为二种:二进制文件ASCII文件(也就是我们常说的文本文件),图形文件及文字处理程序等计算机程序都属于二进制文件。这些文件含有特殊的格式及计算机代码。ASCII 则是可以用任何文字处理程序阅读的简单文本文件。

当然我们遍历目录,依次读取文件内容时,如果根据扩展名来判断是不太准确的,那又怎么判断文件到底是文本文件还是二进制文件呢?我们看下面的实例代码:


/*
时 代 J a v a - N o w J a v a . c o m
*/

import java.io.File;

import java.io.IOException;

import java.io.RandomAccessFile;


public class Main{

    /**

     * Checks whether or not a file is a text file or a binary one.

     * 

     * @param file - The file to check.

     * @return true if the File is a text file, false otherwise.

     * @throws IOException I/O error.

     * @throws IllegalArgumentException If the file is null or is not a file.

     */

    // CHECKSTYLE:OFF

    public static boolean isText(final File file) throws IOException,

            IllegalArgumentException {


        if (file == null || !file.isFile())

            throw new IllegalArgumentException(// 来 自 n o w j a v a . c o m

                    "Must not be null & must be a file.");

        RandomAccessFile raf = null;


        try {

            raf = new RandomAccessFile(file, "r");

            int numberOfNonTextChars = 0;

            while (raf.getFilePointer() < raf.length()) {

                final int b = raf.readUnsignedByte();

                if (b == 0x09 || // horizontal tabulation

                        b == 0x0A || // line feed

                        b == 0x0C || // form feed

                        b == 0x0D || // carriage return

                        (b >= 0x20 && b = 0x80 && b = 0xA0 && b <= 0xFF)) // latin-1 symbols

                {

                    // OK

        &nb
展开阅读全文