按字节比较文件



我想逐个字节比较两个相同大小的文件以获得重复性。

我正在使用此代码进行比较,但它不起作用:

boolean match=true;                    
BufferedInputStream fs1;
                    BufferedInputStream fs2;
                    byte[] f1 = new byte[(int)f1size],f2=new byte[(int)f2size];
                    try {
                        fs1 = new BufferedInputStream(new FileInputStream(file1));
                        fs2 = new BufferedInputStream(new FileInputStream(file2));
                        fs1.read(f1, 0, f1.length);
                        fs2.read(f2, 0, f2.length);
                        fs1.close();
                        fs2.close();
                        for(int k=0;k<f1.length;k++)
                            if(f1[k]!=f2[k])
                            {
                                match=false;
                                break;
                            }
                        if(match)
                        {
                            Toast.makeText(getApplicationContext(), "Same File", Toast.LENGTH_SHORT).show();
                        }
                    } catch (FileNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

任何人都可以帮助如何逐字节比较文件

InputStream.read() 方法不能保证读取请求的所有字节;您必须检查返回值。

此外,对于大文件,这样做会使用过多的内存;您可能需要考虑循环读取块,除非已知文件总是很小。

无需分配巨大的数组,BufferedInputStream为您进行缓冲。

BufferedInputStream fs1, fs2;
fs1 = new BufferedInputStream(new FileInputStream(file1));
fs2 = new BufferedInputStream(new FileInputStream(file2));
boolean match;
do {
    int b1 = fs1.read(),
        b2 = fs2.read();
    match = b1 == b2;
} while (match && b1 != -1);

最新更新