I have set up a JUnit test that is testing a method called copy(File src, File dest) that simply copies the contents of the src file to the dest file. I am using a Scanner to iterate over each file simultaneously (two different Scanners of course), and then comparing each Scanners next() with .equals().
This test fails, telling me the files are not equal. But how can this be? The strings look identical when I print them, not to mention I did a hex dump of the files right after the call to copy() and those look identical as well. However, when I print each value of next() in bytes, I do indeed get different byte patterns. I am confused as to why this is happening, and what changes I can make to my code to account for this?
My thinking is that it has something to do with the encoding of the files, perhaps the encoding method used to create the files is different then the one used by copy() elsewhere in the program? Really not too sure, any help is appreciated! Here is what I am working with for the test unit:
// The @Rule and @Before blocks are used as set up helper methods for @Test.
@Rule
public TemporaryFolder tmp = new TemporaryFolder();
private File f1, f2;
@Before
public void createTestData() throws IOException {
f1 = tmp.newFile("src.txt");
f2 = tmp.newFile("dest.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(f1));
out.write("This should generate some " +
"test data that will be used in " +
"the following method.");
out.close();
}
@Test
public void copyFileTest() throws FileNotFoundException,
Exception {
try {
copyFile(f1, f2);
} catch (IOException e) {
e.getMessage();
e.printStackTrace();
}
Scanner s1 = new Scanner(f1);
Scanner s2 = new Scanner(f2);
// FileReader is only used for debugging, to make sure the character
// encoding is the same for both files.
FileReader file1 = new FileReader(f1);
FileReader file2 = new FileReader(f2);
out.println("file 1 encoding: " +file1.getEncoding());
out.println("file 2 encoding: " +file2.getEncoding());
while (s1.hasNext() && s2.hasNext()) {
String original = s1.next();
String copy = s2.next();
// These print out to be the same ...
out.println("\ns1: " +original);
out.println("s2: " +copy);
// Nevertheless, this comparison fails!
// These calls to getBytes() return different values.
if (!(s1.equals(s2))) {
out.println("\nComparison failed!! \ns1 in bytes: " +original.getBytes()+
"\ns2 in bytes: " +copy.getBytes());
fail("The files are not equal.");
}
}
}
And here is my output:
file 1 encoding: UTF8
file 2 encoding: UTF8
s1: This
s2: This
Comparison failed!!
s1 in bytes: [B@16f5b392
s2 in bytes: [B@5ce04204
Scannerdoesn’t overrideObject.equals(), so it’s comparing references, which in your case are not equal since you you have two separateScannerobjects.