0

I want to compare two same size files byte by byte for duplicacy.

I'm using this code to compare but it's not working:

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();
                    }

Can Anybody help how to compare files byte by byte

4

2 回答 2

2

The InputStream.read() method is not guaranteed to read all the bytes asked for; you have to check the return value.

Also, for large files doing it this way will use excessive memory; you may want to consider reading chunks in a loop unless the files are known to be always small.

于 2012-12-19T09:46:05.827 回答
1

No need to allocate huge arrays, BufferedInputStream does buffering for you.

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);
于 2012-12-19T10:01:14.320 回答