Revision as of 16:58, 22 March 2011 by Han84 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
/**
 * Compare the contents of two files.
 * @param fileName1
 * @param fileName2
 * @return
 */
public static boolean fileIsIdentical(String fileName1, String fileName2) {
	return Ts.fileIsIdentical(new java.io.File(fileName1), new java.io.File(fileName2));
}
public static boolean fileIsIdentical(java.io.File file1, java.io.File file2) {
	long crc1 = Ts.fileCRC32(file1);
	long crc2 = Ts.fileCRC32(file2);
	if (crc1 != crc2) {
		return false;
	}
	java.io.BufferedInputStream in1 = Ts.convertFileToBufferedInputStream(file1);
	java.io.BufferedInputStream in2 = Ts.convertFileToBufferedInputStream(file2);
	int c1 = 0, c2 = 0;
	try {
		while ((c1 = in1.read()) != -1 && (c2 = in2.read()) != -1) {
			if (c1 != c2) {
				return false;
			}
		}
		c2 = in2.read();
		in1.close();
		in2.close();
	} catch (java.io.IOException ex) {
		Ts.printErr(ex);
	}
	// If c1 == c2 == -1.
	// This means that the lengths of two files are identicla.
	if (c1 == c2) {
		return true;
	} else {
		return false;
	}
}
 
public static long fileCRC32(java.io.File file) {
	java.util.zip.Checksum crc = new java.util.zip.CRC32();
	try {
		java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.io.FileInputStream(file));
		byte buff[] = new byte[32768];
		int len = 0;
		while ((len = in.read(buff)) >= 0) {
			crc.update(buff, 0, len);
		}
		in.close();
	} catch (java.io.IOException ex) {
		Ts.printErr(ex);
	}
	return crc.getValue();
}
 
public static void printErr(java.lang.Exception ex) {
	ex.printStackTrace();
	System.exit(-1);
}
 
public static java.io.BufferedInputStream convertFileToBufferedInputStream(java.io.File file) {
	java.io.BufferedInputStream bis = null;
	try {
		bis = new java.io.BufferedInputStream(new java.io.FileInputStream(file));
	} catch (java.io.FileNotFoundException ex) {
		Ts.printErr(ex);
	}
	return bis;
}


Back to JavaHowTo

Alumni Liaison

Ph.D. on Applied Mathematics in Aug 2007. Involved on applications of image super-resolution to electron microscopy

Francisco Blanco-Silva