Java File I/O :Reader/Writer and when a Stream

来源:互联网 发布:如何推广淘宝网店 编辑:程序博客网 时间:2024/05/01 13:35

1. XXXInputStream and XXXOutputStream (where XXX varies, there's a lot of options) deal with 8-bit bytes. For example,OutputStream.write(byte[] c);

2. XXXWriter or XXXReader deal with 16-bit chars. For example, Reader.read(char[] cbuf).

3. OutputStreamWriter converts an OutputStream to a Writer.

4. InputStreamReader converts from an InputStream to a Reader.


5.FileWriter is a Writer that talks to files.

Since a Java String internally uses chars (16 bit so they can handle Unicode), FileWriter is the natural class for use with Unicode Strings.


6. FileOutputStream is an OutputStream for writing bytes to a file. OutputStreams do not accept chars (or Strings).

By wrapping it in an OutputStreamWriter you now have a Writer, which does accept Strings.


Now, the real question, is when do you use a Reader/Writer and when a Stream? I've used Java for years and sometimes I get confused too. I believe the following to be correct:

  1. If you are dealing with binary data (e.g. an image) use Streams.
  2. If you are using non-ASCII Unicode characters, e.g. Chinese, useReaders/Writers.
  3. If you are using ordinary ASCII text (the traditional 0-127 characters) you can (usually) use either

other references :

http://www.vogella.com/articles/JavaIO/article.html

http://stackoverflow.com/questions/4576222/fastest-way-to-write-to-file

inputstream and reader in Java IO

InputStream vs InputStreamReader


原创粉丝点击