0

I've used this topic: File to byte[] in Java Here is my code:

try {
  Path path1 = Paths.get(path + fileName);
  byte[] fileAsByte = Files.readAllBytes(path1);
  System.out.println("Byte : " + fileAsByte.toString());
} catch (FileNotFoundException e) {
  System.out.println("File Not Found.");
  e.printStackTrace();
} catch (IOException e1) {
  System.out.println("Error Reading The File.");
  e1.printStackTrace();
} catch (OutOfMemoryError e3) {
  System.out.println("Out of Memory");
  e3.printStackTrace();
  }

This code is not triggering any exception, but the output is still:

Byte : [B@60f17a2f

Which seems pretty invalid to me. I'm pretty sure I did a dumb error, but it's been three hours that I've been trying to resolve it, and I could use some fresh eyes on it.

Thanks.

Community
  • 1
  • 1
Bdloul
  • 882
  • 10
  • 27

2 Answers2

4

You can't convert an array directly to String and have it readable by the human eye. It is printing out [ (meaning "array"), then B (for byte), then @ and its identity hash code.

To get a list of the bytes in the array, use the static Arrays.toString() method instead:

System.out.println("Byte : " + java.util.Arrays.toString(fileAsByte));

(If the bytes represent characters for an output string, use @iTech's solution.)

Community
  • 1
  • 1
Cat
  • 66,919
  • 24
  • 133
  • 141
4

You should create a String instance initialized with your byte[], e.g.

System.out.println("Byte : " + new String(fileAsByte));

You can also specify the encoding e.g. new String(fileAsBytes,"UTF-8");

iTech
  • 18,192
  • 4
  • 57
  • 80