Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 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
share|improve this answer
    
If you like this answer, can you mark it as accepted? Thank you! –  Brett Jul 31 '13 at 18:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.