I’m reading Eckel’s book, IO chapter, and there is the following code (p. 667).
public static void main(String[] args) throws IOException {
try {
DataInputStream in = new DataInputStream(new ByteArrayInputStream(BufferedInputFile.read("src/io/FormattedMemoryInput.java").getBytes()));
while(true) {
System.out.print((char)in.readByte()); // problem line
}
} catch (EOFException ex) {
System.err.println("End of stream");
}
}
This code works great, but if i change (char) in.readByte() to in.readChar() it prints me some asian symbols 灡捫慧攠楯㬊੩浰潲琠橡癡漮⨻੩浰. Why is that and why it doesn’t print english ASCII symbols out?
From
DataInput.readChar():In other words, it’s treating your file as if it’s UTF-16-encoded – and it almost certainly isn’t.
When you want to read text data you should use a
Readersubclass, e.g.InputStreamReaderwrapped aroundFileInputStream, specifying the appropriate encoding for the input data.