I suspect the confusion comes from trying to write text using classes designed to write binary. If you want to write/read text use Writer/Reader classes. If you want binary use OutputStream/InputStream.
PrintWriter pw = new PrintWriter("ccc.txt");
pw.println('C');
pw.println(67);
pw.close();
will produce a file which looks like
C
67
but in reality you have written a file which contains bytes 67, 19, 16, 54, 55, 19, 16 i.e it is now 7 bytes long.
what is the difference between the two methods if they both simply write two bytes to the outputstream?
They do exactly the same thing in this case. The difference only matters for the readChar / readShort.
public final void writeChar(int v) throws IOException {
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
incCount(2);
}
public final void writeShort(int v) throws IOException {
out.write((v >>> 8) & 0xFF);
out.write((v >>> 0) & 0xFF);
incCount(2);
}
You can see the code is the same.
I was expecting that writeShort can write two bytes to the outputstream and then transfer it back to integer.
A file only contains a stream of bytes.
In other words, how can I directly write the integer 67 to a file,not converting it to a character?
That is what you are doing. A file only contains bytes. When you read text you are converting these bytes into char
s, or short
s or int
s depending on how you read them.