ITeye博客

比较两个文件是否相等

sanpic · 2010-08-14 23:56 · java点点滴滴 · 编程语言 · Markdown

可以比较两个任意格式的文件,但文件不能太大。如果文件太大,可以分割文件比较,因为会在“ byte[] data1 = new byte[len1];”报错,所以要在“todo”里面增添新的方法。

 

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileCompare
{
    public FileCompare()
    {
        boolean isEqa = verifyFile("f://file1.flv", "f://file2.flv");
        System.out.println(isEqa);
    }

    private boolean verifyFile(String fileName1, String fileName2)
    {
        FileInputStream fis1 = null;
        FileInputStream fis2 = null;
        try
        {
            fis1 = new FileInputStream(fileName1);
            fis2 = new FileInputStream(fileName2);
            int len1 = fis1.available();
            int len2 = fis2.available();
            if (len1 == len2)
            {
                byte[] data1 = new byte[len1];
                byte[] data2 = new byte[len2];
                fis1.read(data1);
                fis2.read(data2);
                for (int i = 0; i < len1; i++)
                {
                    if (data1[i] != data2[i])
                    {
                        return false;
                    }
                }
                return true;
            } else
            {
                return false;
            }
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } catch (OutOfMemoryError e)
        {   //todo:分割方法
            e.printStackTrace();
        } finally
        {
            closeFileStream(fis1, fis2);
        }
        return false;
    }

    private void closeFileStream(FileInputStream fis1, FileInputStream fis2)
    {
        if (fis1 != null)
        {
            try
            {
                fis1.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        if (fis2 != null)
        {
            try
            {
                fis2.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {
        new FileCompare();
    }
}

 

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。