关于java:如何打开文件来读取文件的所有字节?

How to open a file to read all bytes of the file?

本问题已经有最佳答案,请猛点这里访问。

我想读取一个文件中的所有字节,但当我这样做时

1
2
3
Path fileLocation = Paths.get("./env.wav");
byte[] data = Files.readAllBytes(fileLocation);
System.out.println(data);

它只输出:

[B@6ab1bd82

而不是像这样输出字节数组:

249 4646 ac98 0200 5741 5645 666d 7420
1000 0000 0100 0100 44ac 0000 8858 0100
0200 1000 6461 7461 8898 0200 7900 5200
5600 3b00 3100 0c00 6500 4000 2500 7a00
2d00 0c00 5400 5100 2500 1200 feff 0d00 [etc..............]


使用array.toString()。打印数组将打印其toString(),默认为对象的toString()。

1
2
3
Path fileLocation = Paths.get("./env.wav");
byte[] data = Files.readAllBytes(fileLocation);
System.out.println(Arrays.toString(data));


您正在直接打印阵列。当前打印的值是数组的内存位置。

如果需要数组的内容,则需要将其强制转换为可打印的内容,或者循环转换内容并打印每个字节(将每个字节强制转换为可打印的值)。

一种方法是:如何将字节数组中的数据打印为字符