1

Is there any way to compare 2 text (ODT) files without using loops?

The point is, inside a servlet, I'm receiving a file from JavaScript and I want to compare it with another stored in the server. This is what I'm doing, but it isn't working, it says that they are not equals, but they are, their contents are exactly the same given they are the same files.

I receive the content of the file in base64 and I parse it to byte[] (content var), then I open the stored file (savedFile var) and parse it to byte[] (savedFileByte var). Then I try to compare both byte[] vars using Arrays.equals(). As I said, it always return false, however I'm sure that the content is the same. So what I'm doing wrong? Or, is there another way to handle this?

I don't want to use loops because this maybe will compare lot of files, so using loops would decrease performance. Anyway, if it's the only way, say it! Thanks!

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String fileName = String.valueOf(request.getParameter("fileName"));

    byte[] content = Base64.decodeBase64(IOUtils.toByteArray(request.getInputStream()));

    FileInputStream savedFile = new FileInputStream("path/"+fileName);

    byte[] savedFileByte = IOUtils.toByteArray(savedFile);

    if (Arrays.equals(content, savedFileByte))
        System.out.println("MATCH!");
    else
        System.out.println("DO NOT MATCH!");

    savedFile.close();
}
Drumnbass
  • 867
  • 1
  • 14
  • 35

1 Answers1

0

You can use Apache Commons contentEquals. But you must know that internally, the loop will happen....

Example:

File file1 = new File("test1.odt");
File file2 = new File("test2.odt");

boolean compare1and2 = FileUtils.contentEquals(file1, file2);

System.out.println("Are test1.txt and test2.txt the same? " + compare1and2);

To convert from byte[] to File use also Apache Commons writeByteArrayToFile or:

FileOutputStream fos = new FileOutputStream("pathname");
fos.write(myByteArray);
fos.close();
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • But how do I convert the byte[] data into a `File` object? – Drumnbass May 25 '15 at 08:04
  • Check [here](http://www.mkyong.com/java/how-to-convert-array-of-bytes-into-file/) and [here](http://stackoverflow.com/questions/4350084/byte-to-file-in-java) and my question's edit – Jordi Castilla May 25 '15 at 08:05