Question

This is the code that I use to copy sharedpreference file toand fro from sdcard.

File fileSrc = new File(filePath, "userdata.xml");
File fileDes = new File("/data/data/com.nik/shared_prefs/", "userdata.xml");
...
...
private void copyFile(File fileSrc, File fileDes) {
FileInputStream fileinputstream=null;
FileOutputStream fileoutputstream=null;
try {
fileinputstream = new FileInputStream(fileSrc);
fileoutputstream = new FileOutputStream(fileDes);
byte[] buffer = new byte[4096];
int count = 0;
while ((count = fileinputstream.read(buffer)) > 0) {
    fileoutputstream.write(buffer, 0, count);
}
fileinputstream.close();
fileoutputstream.flush();
fileoutputstream.close();
}
catch(IOException e) {
    e.printStackTrace();
}
}
if(fileSrc.hashCode() == fileDes.hashCode()){
    Log.d("Copy result: ", "Files Equal!");
} else {
    Log.d("Copy result: ", "Files not Equal!");
}
if(fileSrc == fileDes){
    Log.d("=>Copy result: ", "Files Equal!");
} else {
    Log.d("=>Copy result: ", "Files not Equal!");
}
}

The above code runs successfully and copies the file, but it always shows "Files not Equal!" in Log.

If I open the file in explorer, the content is same. So why am I getting the "Files not Equal!" in both the cases.....

EDIT:

I created the following method to create SHA-256 hash of a file

private MessageDigest fileHash(File file) {
    MessageDigest md=null;
    try {
    md = MessageDigest.getInstance("SHA-256");
    FileInputStream fileinputstream = new FileInputStream(file);
    byte[] dataBytes = new byte[1024];
    int nread = 0;
    while ((nread = fileinputstream.read(dataBytes)) != -1) {
        md.update(dataBytes, 0, nread);
    }
    }
    catch(IOException e) {
        e.printStackTrace();
    }
    catch(NoSuchAlgorithmException e){
        e.printStackTrace();
    }
    return md;
}

and called it with

if(fileHash(fileSrc) == fileHash(fileDes)){
Log.d("=>Copy result: ", "Files Equal!");
} else {
Log.d("=>Copy result: ", "Files not Equal!");
}

Still i m getting "Files not Equal!".

Was it helpful?

Solution

File.hashCode() returns a hash code derived from the file object, i.e. basically the file name. It does not hash the contents of the file on disk. Since the two file names are different there is a good chance that the hash codes are different as well.

Answer to the edit: You compare now two message digest objects, not the hashes of the files. Since the objects are different, you get again non-equality.

Instead you should return the hash sum from the function:

private byte[] fileHash(File file) {
    ...
    return md.digest();
}

and compare them like this:

if (Arrays.equals(fileHash(fileSrc), fileHash(fileDes))) { ... }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top