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

zhuguowei

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?

Scary Wombat

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related