我有一个包含 java ByteArray 的文件。
字节.inc
byte MyByteArray[] = new byte[]
{
(byte) 0x4D,(byte) 0x5A,(byte) 0x50,(byte) 0x00,(byte) 0x02,(byte) 0x00,(byte) 0x00,
(byte) 0x00,(byte) 0x04,(byte) 0x00,(byte) 0x0F,(byte) 0x00,(byte) 0xFF,(byte) 0xFF,
(byte) 0x00,(byte) 0x00,(byte) 0xB8,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x40,(byte) 0x00,(byte) 0x1A,(byte) 0x00,
(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x01,(byte) 0x00,
(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
};
完整文件 (bytes.inc) 为 283kb,对于编译器来说太大了,无法插入到特定类中。我尝试过逐字节读取文件,然后将其从字符串转换为实际字节,因为读取文件只会产生字符串,当我这样做并将一个字节转换回它时,它会显示字节的文本表示,而不是实际字节转换。 我怎样才能获得生成完整 ByteArray 的能力,而无需将其包含到一个巨大的方法中?
最佳答案
一种选择是将实际字节存储在文件中并使用 Files.readAllBytes(path)
读取它们
Path path = Paths.get("path/to/file");
byte[] bytes = Files.readAllBytes(path);
另一种选择是将字节作为文本保存在文件中
以,
分隔,使用如下代码:
FileReader file = new FileReader("bytes.txt");
Scanner scanner = new Scanner(file);
scanner.useDelimiter(",");
ByteBuffer byteBuffer = new ByteBuffer(0);
while (scanner.hasNext()) {
byteBuffer.append(Byte.decode(scanner.next().trim()));
}
scanner.close();
字节文件看起来像:
0x4D,0x5A,0x50,0x00,0x02
关于Java ByteArray 文件解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17009097/