• Post Reply Bookmark Topic Watch Topic
  • New Topic

reader vs stream  RSS feed

 
George Dee-Brown
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
does a "Reader" read 1 byte at a time? I tought since a reader is intended to be used for characters it would read 1 unicode (16 bit) char at a time, but when I wrote:
stream.writeByte((byte)69);
stream.writeChars("ABC");
to a file using a stream then read the same file using a reader I got:
System.out.println((char)br.read()); // prints E
System.out.println((char)br.read()); // prints nothing
System.out.println((char)br.read()); // prints A
System.out.println((char)br.read()); // prints nothing
System.out.println((char)br.read()); // prints B
System.out.println((char)br.read()); // prints nothing
System.out.println((char)br.read()); // prints C
It looks like the reader is reading 1 byte at a time!
Any opinions?
...George
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume you created a FileReader to do the reading, right? This uses the default encoding of your platform. To find out what this is, use
<code><pre>System.out.println(new InputStreamReader(System.in).getEncoding());</pre></code>
Chances are, it's a one-byte encoding like US-ASCII or ISO-LATIN-1. Which means yes, it reads one byte at a time. Try constructing a reader like this instead:
<code><pre>Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-16");</pre></code>
This will make a reader which assumes each Unicode value was written directly using 16 bits.
Actually though, if you used a DataOutputStream to write the characters uing writeChars(), you should probably use a DataInputStream to read them. This means forget about readers and specifying encoding with InputStreamReader - the data streams handle this differently. There is a little problem in that there is no readChars() method; only readChar(). A readChars() method would have no way of knowing how many chars to read. There are a lot of ways you could specify this, but the easiest is probably to use writeUTF() and readUTF() instead. It's instructive to read the APIs for all these methods carefully - there are a lot of subtleties, and a lot of ways you can read and write data. Enjoy...
[This message has been edited by Jim Yingst (edited July 22, 2001).]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!