On 4/23/2012 6:52 PM, bilsch wrote:
> I HAVE TWO QUESTIONS: the statement: int input = file.read();
> reads the file as a bunch of integer type values but the output is in
> character type. It seems like the correct input statement would be:
> char input = file.read();
> I tried that and it is an error. QUESTION 1): Can someone explain why
> the file is read as char type but the statement says int type?
The file is not read as a char type. A Java char is a UTF-16 codepoint.
InputStreams treat their inputs as a stream of byte elements. However,
it is also necessary for the read() method to return a sigil that
indicates that the end of the file has occurred, which means it cannot
use the byte type since the sigil would override a valid character. The
type returned is instead widened to an int, with the values 0-255
indicating a valid octet in the file and the value -1 indicating that
the end-of-the-file has been reached.
> QUESTION 2) What do I need to do to get ASCII characters as output
> instead of numbers?
The best way is to not use an InputStream in the first place but instead
use a FileReader.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth