0

I'm working on a simple VM/interpreter kind of program for a simple toy language I implemented. Currently the compiler emits textual assembly instructions such as push and add to be executed by the VM.

Recently I figured it would be a better idea to actually compile to binary opcodes instead of textual ones, for performance and space. (It doesn't actually matter in this toy project, but this is for learning).

Soon I realized, even though generally I consider myself a decent Java programmer, that I have no idea how to work with binary data in Java. No clue.

Regarding this, I have two questions:

  1. How can I save binary data to a file? For example say I want to save the byte 00000001 and then the byte 00100000 to a file (each byte will be an opcode for the VM) - how can I do that?

  2. How can I read binary data from a file on disk, save it in variables, parse it and manipulate it? Do I use the usual I/0 and parsing techniques I use with regular Strings, or is this something different?

Thanks for your help

0

4 Answers 4

0

You should be able to use any OutputStream to do this, because they all have a write method that takes a byte. For example, you could use a FileOutputStream.

Similarly, you can use an InputStream's read method for reading bytes.

Sign up to request clarification or add additional context in comments.

Comments

0

OutputStream and its subtypes have methods to write bytes to files. DataOutputStream has additional methods to write int, long, float, double, etc. if you need those, although it writes them in big endian byte order. The corresponding input streams have equivalent methods for reading.

Comments

0

You may want to try to use ByteArrayInputStream and DataOutputStream

Refer to the Oracle documentation for details.

Also, checkout this similar question: How to output binary data to a file in Java?

2 Comments

ByteArrayInputStream is for reading from a byte array in memory. It does not read from a file on disk.
Reading from the file is just as usual (or via FileUtils by Apache, commons.apache.org/proper/commons-io/apidocs/org/apache/commons/…). The interesting part is your point 2 (as long as I understand your question), where you ask how to manipulate the read data.
0

Use a FileOutputStream. It has a write(byte[] b) method to write an array of bytes to a file and a write(int b) method to write a single byte to the file.

So, to save 00000001 followed by 00100001, you can do :

FileOutputStream file = new FileOutputStream(new File(path));
file.write(1);
file.write(33);

Similarly you can read FileInputStream for reading from a binary file.

2 Comments

ByteArrayOutputStream is a way to write to a byte array in memory. OP wants to write binary data to disk.
@DavidConrad My mistake. That's what happens when I rely on my memory before checking the JavaDoc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.