flea whale
flea whale

Reputation: 1803

Why does out.write() alter int values in Java?

I'm trying to output some data to file in Java and do not understand why when I run this code...

try {
    File file = new File("demo.txt");
    BufferedWriter out = new BufferedWriter(new FileWriter(file));
    int i = 127;
    int j = 128;
    System.out.println(Integer.toHexString(i));
    System.out.println(Integer.toHexString(j));
    out.write(i);
    out.write(j);
    out.close();
} catch (IOException e) {}   

...the following is output to the console log:

7f
80

but when I open the file demo.txt with a hex editor I see the bytes 7f and 3f. Why does out.write() output most int values correctly (example 127) but alters others (example 128)? How can I write the data to the file straight?

Upvotes: 1

Views: 761

Answers (1)

ARRG
ARRG

Reputation: 2496

FileWriter should be used to write character streams. If you are trying to write binary data, then a FileOutputStream is appropriate. If you replace your FileWriter with a FileOutputStream and your BufferedWriter with a BufferedOutputStream you will find that the data is written as you'd expect.

FileWriter is character and encoding-aware which means that it may transform data that you pass through it to match a character encoding. But to be honest I don't know exactly what transformation is going on here.

Upvotes: 3

Related Questions