mk.. mk.. - 2 months ago 13
Java Question

Java - Read mixed data types from a file (char + int + binary)

I am reading data from a file (Actually a fifo pipe).

The format is as follows

SECTION_NAME
SECTION_SIZE
SECTION_DATA[SECTION_SIZE]
.....


Ex:

pps_frame
1404
<Binary data of 1404 bytes>
sps_frame
1000
<Binary data of 1000 bytes>
...


How do i Read the binary data of 1404 bytes in the above example. Note that the
SECTION_SIZE
keeps varying.

PS: In my native code, I am writing this data into the pipe.

Answer

Unfortunately that is indeed a bit circumstantial: first reading text, and then binary data. Here a solution, staying with binary reading.

FileInputStream fin = ...
BufferedInputStream bin = new BufferedInputStream(fin, 2048);
String name = readLine(bin);
String lineWithSize = readLine(bin);
int size = Integer.parseInt(lineWithSize);
byte[] data = new byte[size];
bin.read(data, 0, size);
bin.close();

With a help function readLine for reading bytes, and converting them to text. As BufferedReader.readLine it discards the line endings, here following the simplified assumption that a line ending is either LF or CR+LF.

String readLine(BufferedInputStream bin) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    for (;;) {
        int ch = bin.read();
        if (ch == -1) {
            break;
        }
        if (ch == '\r' || ch == '\n') {
            if (ch == '\r') {
                bin.read();
            }
            break;
        }
        baos.write(ch);
    }
    return baos.toString("ISO-8859-1"); // Basic Latin-1 encoding.
}

Reading text with a Reader does always a conversion of bytes using some encoding of those bytes. To its internal Unicode (a char is two bytes UTF-16). Hence you cannot 100% perfectly read bytes into a String. Because of size and conversion it is not even desirable.

Comments