Read from byte array to console (or file) Java

1.7k views Asked by At

So I have two files, a binary file that I have read into a byte array, and a text file that I have read into an ArrayList of Strings. Now lets assume my ArrayList has the values "char", "int", "double" and serves as the schema for reading my binary file.

That means for the first two bytes in the byte array I want to interpret as a char, the next four as an int, and the next 8 as a double, and this will repeat itself until the file is over.

I've implemented reading in all the data, but I can't figure out a good way to properly interpret the binary data according to the schema file. Is there a good way to do this?

IE (psuedocode) using PrintStream out = new PrintStream (new OutputStream(byteArray)) out.writeChar() out.writeInt() out.writeDouble()

Where the Stream works through the byteArray for me? (As opposed to me saying out.writeChar(byteArray[2])?

I have figurd out all the logic of mapping the schema to the proper action, but I am having trouble properly converting the data. Any thoughts?

I want to write this information to either the console (or a file).

2

There are 2 answers

0
Seelenvirtuose On BEST ANSWER

Think object-oriented! You have to create a class for each desired data type, which is capable of parsing the data in an input stream.

Steps are (without caring about exceptions):

1) Create an interface for these classes:

interface DataParser {
    void parse(DataInputStream in, PrintStream out);
}

2) Create a class for each data type implementing that interface. Example:

class IntParser implements DataParser {
    public void parse(DataInputStream in, PrintStream out) {
        int value = in.readInt();
        out.print(value);
    }
}

3) Use a HashMap for registering all known parsers with their String ID:

Map<String, DataParser> parsers = new HashMap<>();
parsers.put("int", new IntParser());

4) Now you can use it like this:

DataInputStream in = ... ;
PrintStream out = ... ;
...
while(hasData()) {
    String type = getNextType();
    DataParser parser = parsers.get(type);
    parser.parse(in, out);
}
// close streams and work on the output here

The method hasData should determine, whether there is still data in the input stream. The method getNextType should return the next type string from your ArrayList.

0
Oren Ezer On

if you need only primitive types or strings you should use DataInputStream to wrap your data:

DataInputStream myDataInputStream=new DataInputStream(myByteInputStream);
myDataInputStream.readDouble();
myDataInputStream.readInt();
myDataInputStream.readChar();
myDataInputStream.readLong();