Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why byte array converted to string then convert back to byte array is not same?

First read excel as byte array, then convert this byte array to string, then convert this string to byte array again.

        String fileLocation = "/tmp/a.xlsx";
        byte[] bytes1 = Files.readAllBytes(Paths.get(fileLocation));
        String str = new String(bytes1);
        byte[] bytes2 = str.getBytes();
        System.out.println(Arrays.equals(bytes1, bytes2)); // false

Why bytes1 is not equals to bytes2?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you are converting from bytes to a String

String str = new String(bytes1);

you are potentially losing non-char bytes.

As per the javadocs

The behavior of this constructor when the given bytes are not valid in the default charset is unspecified.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading