2

I have a file that contains a java ByteArray.

bytes.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,
};

The full file (bytes.inc) is 283kb which is too much for the compiler to allow me to insert into a specific class. I have tried reading the file as just byte by byte then convert it from a string to an actual byte because reading files only produces strings, when I do that and convert a byte back it shows a textual representation of the byte, and not its actual conversion. How can I go about getting the ability to produce the full ByteArray without including it into a huge method?

1 Answer 1

1

One option is to store the actual bytes in a file and read them using Files.readAllBytes(path)

Path path = Paths.get("path/to/file");
byte[] bytes = Files.readAllBytes(path);

Another option is to keep the bytes as text in a file separated by , and use the following code:

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();

The byte file would look like:

0x4D,0x5A,0x50,0x00,0x02
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.