I am currently learning basic I/O of java. Please see the following code:
import java.io.DataOutputStream;
import java.io.IOException;
public class TestIO {
public static void main(String[] args) {
try(DataOutputStream out=new
DataOutputStream(new FileOutputStream("e:\\ccc.txt"))){
out.writeShort(67);
out.writeChar(67);
}catch(IOException ex){
ex.printStackTrace();
}
}
}
In the output ccc.txt file, I get the following output:
C C
I understand that both methods write two bytes to the outputstream and the binary string of 67 is 1000011 which represents the capital letter C in ASCII or anyother code. The space before C is the byte 0000 0000 read by the methods.
However, what is the difference between the two methods if they both simply write two bytes to the outputstream?I was expecting that writeShort can write two bytes to the outputstream and then transfer it back to integer. In other words, how can I directly write the integer 67 to a file,not converting it to a character?
Let me ask this question in a different way, under what circumstance can these two methods generate different results? I need a real-world example. Thanks!
However, what is the difference between the two methods if they both simply write two bytes to the outputstream?
This sounds trite, but: one takes a char
, the other takes a short
. Those types aren't convertible to each other, and you use them at different times. Even though a char
is just a 16-bit unsigned integer, its expected use is for UTF-16 code units; you wouldn't (or at least shouldn't) use it to store values you think of as numbers... and the opposite is true for short
.
So if you've got a char
that you want to write, use writeChar
. If you've got a short
, use writeShort
. In both cases you'd want to read with the corresponding method.
See more on this question at Stackoverflow