---
title: "Java io 浅析"
author: "Flory"
date: "2013-01-21T17:48:00Z"
tags: []
slug: "java-io"
draft: false
lastmod: "2015-09-01T16:27:08Z"
id: 2240002
url: "https://flory.iteye.com/blog/2240002"
---

**什么是流：**

流是一个抽象的概念。当Java程序需要从数据源读取数据时，会开启一个到数据源的流。数据源可以是文件，内存或者网络等。同样，当程序需要输出数据到目的地时也一样会开启一个流，数据目的地也可以是文件、内存或者网络等。流的创建是为了更方便地处理数据的输入输出。

流分为字节流和字符流。字节流也称为原始数据，需要用户读入后进行相应的编码转换。而字符流的实现是基于自动转换的，读取数据时会把数据按照JVM的默认编码自动转换成字符。

字节流由InputStream和OutputStream处理，而字符流由Reader和Writer处理。Reader和Writer是Java后加入的处理类，出于让数据的处理更方便的目的。

**字节流处理概述：**

对于字节流处理的类都继承自InputStream和OutputStream这两个抽象类。

InputStream提供的最重要的方法是：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/313635 "复制代码") [![收藏代码](http://www.iteye.com/images/icon_star.png)![](http://www.iteye.com/images/spinner.gif)]()

1. read();
2. read(byte\[] b) ;
3. read(byte\[] b, int off, int len) ;

```
read();
read(byte[] b) ;
read(byte[] b, int off, int len) ;
```

用于从输入流中读取字节。

OutputStream提供的最重要的方法是：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/313635 "复制代码") [![收藏代码](http://www.iteye.com/images/icon_star.png)![](http://www.iteye.com/images/spinner.gif)]()

1. write(int b);
2. write(byte\[] b);
3. write(byte\[] b, int off, int len)

```
write(int b);
write(byte[] b);
write(byte[] b, int off, int len) 
```

用于将字节写入输出流。

**字节流处理类概述：**

字节流的处理类有很多，他们都继承自InputStream或者OutputStream抽象类。

输入流：

先谈谈输入流，输入流中跟数据源直接接触的类有：FileInputStream和ByteArrayInputStream，他们分别实现了从文件或者内存中的字节数组读入数据到输入流。

其他的输入流处理类都是装饰类（Decorator模式），下面对他们进行一下简单介绍：

BufferedInputStream： 提供了缓冲功能。

DataInputStream: 允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型。应用程序可以使用数据输出流写入稍后由数据输入流读取的数据。

PipedInputStream: 允许以管道的方式来处理流。当连接到一个PipedOutputStream后，它会读取后者输出到管道的数据。

PushbackInputStream: 允许放回已经读取的数据。

SequenceInputStream: 能对多个inputstream进行顺序处理。

输出流：

基本上每个输入流类都有一个相应的输出流类，提供相应的输出流处理。

同样，跟数据目的地直接接触的类有：FileOutputStream和ByteArrayOutputStream，前者实现了把数据流写入文件的功能，后者实现了一个输出流，其中的数据被写入一个 byte 数组。缓冲区会随着数据的不断写入而自动增长。可使用 `toByteArray()`和 `toString()`获取数据。

下面对其它的装饰类做一下简单介绍：

BufferedOutputStream： 提供了缓冲功能的输出流，在写出完成之前要调用flush来保证数据的输出。

DataOutputStream: 数据输出流允许应用程序以适当方式将基本 Java 数据类型写入输出流中。然后，应用程序可以使用数据输入流将数据读入。

PipedOutputStream: 允许以管道的方式来处理流。可以将管道输出流连接到管道输入流来创建通信管道。管道输出流是管道的发送端。通常，数据由某个线程写入 `PipedOutputStream`对象，并由其他线程从连接的 `PipedInputStream`读取。

PrintStream: 为其他输出流添加了功能，使它们能够方便地打印各种数据值表示形式。我们经常用到的System.out或者System.err都是PrintStream。

**字符流处理概述:**

所有的字符流操作类都继承自Reader或者Writer这两个抽象类。

Reader提供的重要方法有：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/313635 "复制代码") [![收藏代码](http://www.iteye.com/images/icon_star.png)![](http://www.iteye.com/images/spinner.gif)]()

1. read(char\[] cbuf);
2. read(char\[] cbuf, int off, int len);
3. read(CharBuffer target);

```
read(char[] cbuf);
read(char[] cbuf, int off, int len);
read(CharBuffer target);
```

他们提供了从流中读取数据到字符数组或者CharBuffer的功能。

Writer提供的重要方法有：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/313635 "复制代码") [![收藏代码](http://www.iteye.com/images/icon_star.png)![](http://www.iteye.com/images/spinner.gif)]()

1. write(char\[] cbuf);
2. write(char\[] cbuf, int off, int len);
3. write(int c);
4. write(String str);
5. write(String str, int off, int len);

```
write(char[] cbuf);
write(char[] cbuf, int off, int len);
write(int c);
write(String str);
write(String str, int off, int len);
```

他们提供了把字符、字符数组或者字符串写入流中的功能。

**字符流处理类概述：**

输入流：

跟数据源直接接触的类：

CharArrayReader: 从内存中的字符数组中读入数据，以对数据进行流式读取。

StringReader：从内存中的字符串读入数据，以对数据进行流式读取。

FileReader：从文件中读入数据。注意这里读入数据时会根据JVM的默认编码对数据进行内转换，而不能指定使用的编码。所以当文件使用的编码不是JVM默认编码时，不要使用这种方式。要正确地转码，使用InputStreamReader。

装饰类：

BufferedReader：提供缓冲功能，可以读取行：readLine();

LineNumberReader: 提供读取行的控制：getLineNumber()等方法。

InputStreamReader: 字节流通向字符流的桥梁：它使用指定的 `charset`读取字节并将其解码为字符。

输出流：

根数据目的相关的类：

CharArrayWriter：把内存中的字符数组写入输出流，输出流的缓冲区会自动增加大小。输出流的数据可以通过一些方法重新获取。

StringWriter: 一个字符流，可以用其回收在字符串缓冲区中的输出来构造字符串。

FileWriter：把数据写入文件。

装饰类：

BufferedWriter：提供缓冲功能。

OutputStreamWriter：字符流通向字节流的桥梁：可使用指定的 `charset`将要写入流中的字符编码成字节。

PrintWriter: 向文本输出流打印对象的格式化表示形式。

**流处理中的其它方法：**

mark和reset用于重复读取某段的数据，如下代码：

Java代码 [![复制代码](http://www.iteye.com/images/icon_copy.gif)](http://www.iteye.com/topic/313635 "复制代码") [![收藏代码](http://www.iteye.com/images/icon_star.png)![](http://www.iteye.com/images/spinner.gif)]()

01. is = new BufferedInputStream(new FileInputStream("res/input.data"));
02. assertTrue(is.available() &gt; 0);
03. assertTrue(is.markSupported());
04. // The read limit has no effect.
05. is.mark(0);
06. int first = is.read();
07. int second = is.read();
08. is.reset();
09. int firstAgain = is.read();
10. int secondAgain = is.read();
11. assertEquals(first, firstAgain);
12. assertEquals(second, secondAgain);

```
is = new BufferedInputStream(new FileInputStream("res/input.data"));
assertTrue(is.available() > 0);
assertTrue(is.markSupported());

// The read limit has no effect.
is.mark(0);

int first = is.read();
int second = is.read();

is.reset();
int firstAgain = is.read();
int secondAgain = is.read();

assertEquals(first, firstAgain);
assertEquals(second, secondAgain);
```

Writer或者OutputStream中的flush(): 刷新该流的缓冲，用于确保数据的输出。

close(): 关闭流并释放与之关联的所有系统资源。