0

I have a program that needs to read and write RGB values from a file. However, I encountered an issue with the application where the data I am reading back from a file differs from what I was writing to 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
user207421
  • 305,947
  • 44
  • 307
  • 483

1 Answers1

1

A byte is 8 bits, which mean it can store a maximum of 255 (or 128 if signed). When you call fos.write(0xFF95999F), it's casting that to a byte, which means it strips off all but the last two numbers (in hex). If you need to write multiple bytes, you will want to convert your integer into an array of bytes. As suggested in a related SO article, something like

ByteBuffer b = ByteBuffer.allocate(4);
//b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN.
b.putInt(0xFF95999F);

byte[] result = b.array();
fos.write(result);
...

should work better for you. (Why FileOutputStream takes an int instead of a byte I can't answer but I guess it's the same stupid reason why some of the Java methods that get a list (getCookie comes to mind) return null instead of an empty list... premature optimization that they're now stuck with.)

Community
  • 1
  • 1
Foon
  • 6,148
  • 11
  • 40
  • 42
  • There's a difference between an empty list and an absent list. Returning an empty list in the case you mention would only be appropriate if the cookie header was present with no values. – user207421 Apr 29 '15 at 00:31
  • Well, I meant getCookies (http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpServletRequest.html#getCookies%28%29) ... note that there isn't a getCookie method for HttpServletRequest which is another annoyance with that API. – Foon Apr 29 '15 at 00:53