您的位置:首页 > 编程语言 > Java开发

Java IO reader and writer

2011-08-24 16:05 405 查看
Java IO's
Reader
and
Writer
work much like the
InputStream
and
OutputStream
with the exception that
Reader
and
Writer
are character based. They are intended for reading and writing text. The
InputStream
and
OutputStream
were byte based, remember?

Reader

The
Reader
is the baseclass of all
Reader
's in the Java IO API. Subclasses include a
BufferedReader
,
PushbackReader
etc.

Here is a simple example:

Reader reader = new FileReader();

int data = reader.read();
while(data != -1){
char dataChar = (char) data;
data = reader.read();
}

Notice, that while an
InputStream
returns one byte at a time, meaning a value between -128 and 127, the
Reader
returns a
char
at a time, meaning a value between 0 and 65535. This does not necessarily mean that the
Reader
reads two bytes at a time from the source it is connected to. It may read one or more bytes at a time, depending on the encoding of the text being read.

A
Reader
can be combined with an
InputStream
. If you have an
InputStream
and want to read characters from it, you can wrap it in an
InputStreamReader
. Pass the
InputStream
to the constructor of the
InputStreamReader
like this:

Reader reader = new InputStreamReader(inputStream);

In the constructor you can also specify what character set to use to decode the text etc. More on that in the text on
InputStreamReader
.

Writer

The
Writer
class is the baseclass of all
Writer
's in the Java IO API. Subclasses include
BufferedWriter
and
PrintWriter
among others.

Here is a simple example:

Writer writer = new FileWriter("c:\\data\\file-output.txt");

writer.write("Hello World Writer");
writer.close();

A
Writer
can be combined with an
OutputStream
just like
Readers
and
InputStream
's. Wrap the
OutputStream
in an
OutputStreamWriter
and all characters written to the
Writer
are passed on to the
OutputStream
. Here is how that looks:

Writer writer = new OutputStreamWriter(outputStream);


Combining Readers and Writers

Just like with streams,
Reader
's and
Writer
's can be combined into chains to achieve more interesting IO. It works just like combining the
Reader
with
InputStream
's or the
Writer
with
OutputStream
's. For instance, you can achieve buffering by wrapping a
Reader
in a
BufferedReader
, or a
Writer
in a
BufferedWriter
. Here are two such examples:

Reader reader = new BufferedReader(new FileReader(...));

Writer writer = new BufferedWriter(new FileWriter(...)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: