Reputation: 815
public static void main(String[] args) {
try {
File f = new File("file.txt");
f.createNewFile();
OutputStream fos = new FileOutputStream(f);
InputStream fis = new FileInputStream(f);
fos.write(200);
System.out.println(fis.read());
} catch (Exception ex) {
Logger.getLogger(MySimple.class.getName()).log(Level.SEVERE, null, ex);
}
}
this prints 200 as expected. however when I write 2000 it reads 208. could please explain why it behaves in this way?
Upvotes: 0
Views: 40
Reputation: 17435
The method call fos.write(200);
writes a byte of data. When you write 200, it saves that in an 8 bit value just fine.
But when you try to write 2000, it ignores anything above the first 8 bits. 2000 in binary is 0111 1101 0000
. But since the top 4 bits are lost, the resulting value written is 1101 0000
or 208 in decimal.
The methods are a bit confusing since write()
takes an integer value and read()
returns an integer value.
Upvotes: 2