java - DataInputStream.readInt() returns EOFException even if there is still data -


i having lots of trouble reading custom file in java. custom file format consists of called "magic" byte array, file format version , gzipped json-string.

writing file works charm - reading on other side works not intended. eofexception gets thrown when trying read following data length.

i checked produced file hex editor, data gets saved correctly. seems go wrong while datainputstream tries read file.

the read file code:

datainputstream in = new datainputstream(new fileinputstream(file));  // check file header byte[] b = new byte[magic.length]; in.read(b);  if (!arrays.equals(b, magic)) {     throw new ioexception("invalid file format!"); }  short v = in.readshort(); if (v != version) {     throw new ioexception("old file version!"); }  // read data int length = in.readint(); // <----- throws eofexception byte[] data = new byte[length]; in.read(data, 0, length);  // decompress gzip data bytearrayinputstream bytes = new bytearrayinputstream(data); map<string, object> map = mapper.readvalue(new gzipinputstream(bytes), new typereference<map<string, object>>() {}); // mapper the jackson optionmapper  bytes.close(); 

the write file code:

dataoutputstream out = new dataoutputstream(new fileoutputstream(file));  // file header out.write(magic); // 8 byte array (like new byte[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}) identify file format out.writeshort(version); // short (like 1)  // gzip stuff bytearrayoutputstream bytes = new bytearrayoutputstream(); gzipoutputstream gzip = new gzipoutputstream(bytes);  mapper.writevalue(gzip, map); gzip.close();  byte[] data = bytes.tobytearray();  out.writeint(data.length); out.write(data);  out.close(); 

i hope can me out problem (i trying solve thing whole day already)!

regards

i don't think closing both fileoutputstream , gzipoutputstream.

gzipoutputstream requires call close() on when done finish writing out zipped data. require hold onto reference gzipoutputstream.

here think code should be

dataoutputstream out = new dataoutputstream(new fileoutputstream(file));  // file header out.write(magic); // 8 byte array (like new byte[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}) identify file format out.writeshort(version); // short (like 1)  // gzip stuff bytearrayoutputstream bytes = new bytearrayoutputstream(); gzipoutputstream zippedstream =new gzipoutputstream(bytes) mapper.writevalue(zippedstream, /* data */); // mapper   jackson objectmapper, data map<string, object>   zippedstream.close();  byte[] data = bytes.tobytearray();  out.writeint(data.length); out.write(data);  out.close(); 

Comments

Popular posts from this blog

php - get table cell data from and place a copy in another table -

javascript - Mootools wait with Fx.Morph start -

php - Navigate throught databse rows -