001: package abbot.tester;
002:
003: import java.io.*;
004:
005: /**
006: * Compare two files or filenames. Original concept contributed by A. Smith
007: * Montebello.
008: * @author asmithmb
009: * @version 1.0
010: */
011:
012: public class FileComparator implements java.util.Comparator {
013:
014: /**
015: * Read files into streams and call byte by byte comparison method
016: * @param f1 First File or filename to compare.
017: * @param f2 Second File or filename to compare.
018: */
019: public int compare(Object f1, Object f2) {
020:
021: if ((f1 == f2) || (f1 != null && f1.equals(f2)))
022: return 0;
023: // Call null < object
024: if (f1 == null)
025: return -1;
026: // Call object > null
027: if (f2 == null)
028: return 1;
029:
030: File file1, file2;
031: if (f1 instanceof File) {
032: file1 = (File) f1;
033: } else if (f1 instanceof String) {
034: file1 = new File((String) f1);
035: } else {
036: throw new IllegalArgumentException(
037: "Expecting a File or String");
038: }
039: if (f2 instanceof File) {
040: file2 = (File) f2;
041: } else if (f2 instanceof String) {
042: file2 = new File((String) f2);
043: } else {
044: throw new IllegalArgumentException(
045: "Expecting a File or String");
046: }
047: if (file1.equals(file2)) {
048: return 0;
049: }
050:
051: if (!file1.exists() || !file1.isFile()) {
052: throw new IllegalArgumentException("File '" + file1
053: + "' does not exist");
054: }
055: if (!file2.exists() || !file2.isFile()) {
056: throw new IllegalArgumentException("File '" + file2
057: + "' does not exist");
058: }
059:
060: if (file1.length() != file2.length()) {
061: return (int) (file1.length() - file2.length());
062: }
063:
064: InputStream is1 = null;
065: InputStream is2 = null;
066: try {
067: is1 = new BufferedInputStream(new FileInputStream(file1));
068: is2 = new BufferedInputStream(new FileInputStream(file2));
069:
070: int b1 = -2;
071: int b2 = -2;
072: try {
073: while ((b1 = is1.read()) != -1
074: && (b2 = is2.read()) != -1) {
075: if (b1 != b2)
076: return b1 - b2;
077: b1 = b2 = -2;
078: }
079: } catch (IOException io) {
080: return b1 == -2 ? -1 : 1;
081: } finally {
082: is1.close();
083: is1 = null;
084: is2.close();
085: is2 = null;
086: }
087: return 0;
088: } catch (FileNotFoundException fnf) {
089: return is1 == null ? -1 : 1;
090: } catch (IOException io) {
091: return is1 == null ? -1 : 1;
092: }
093: }
094:
095: /** Comparators are equal if they're the same class. */
096: public boolean equals(Object obj) {
097: return obj == this
098: || (obj != null && obj.getClass().equals(getClass()));
099: }
100: }
|