java - Writing bytes to file then reading yields different bytes -
i have program needs read , write rgb values file. however, encountered issue application data reading file differs writing it.
program:
public static void main(string[] args) throws exception { fileoutputstream fos = new fileoutputstream(new file("asdf.txt")); fos.write(0xff95999f); fos.flush(); fos.close(); fileinputstream fis = new fileinputstream(new file("asdf.txt")); byte read; while((read = (byte) fis.read()) != -1) { system.out.print(string.format("%02x ", read)); } fis.close(); } output:
9f
a byte 8 bits, mean can store maximum of 255 (or 128 if signed). when call fos.write(0xff95999f), it's casting byte, means strips off last 2 numbers (in hex). if need write multiple bytes, want convert integer array of bytes. suggested in a related article, like
bytebuffer b = bytebuffer.allocate(4); //b.order(byteorder.big_endian); // optional, initial order of byte buffer big_endian. b.putint(0xff95999f); byte[] result = b.array(); fos.write(result); ... should work better you. (why fileoutputstream takes int instead of byte can't answer guess it's same stupid reason why of java methods list (getcookie comes mind) return null instead of empty list... premature optimization they're stuck with.)
Comments
Post a Comment