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

本文详细介绍了Java中不同类型的IO流,包括InputStream和OutputStream用于处理二进制数据,Reader和Writer用于处理Unicode字符。同时讨论了如何在不同场景下选择合适的流类型,并提供了使用这些流的实际例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值