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();
}

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

But how do I convert the byte[] data into a File object?
Check here and here and my question's edit

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.