---
title: "Java IO流"
author: "crawler"
date: "2013-05-08T09:16:35Z"
tags: []
categories: ["编程语言"]
slug: "java-io"
draft: false
lastmod: "2013-05-08T12:47:26Z"
id: 1862277
url: "https://crawler.iteye.com/blog/1862277"
---

**1.流的概念**

流是一个很形象的概念  
当程序需要读取数据的时候，就会开启一个通向数据源的流，这个数据源可以是文件，内存，或是网络连接。

![](http://dl.iteye.com/upload/attachment/0084/1387/6b381fb4-2104-308f-a3b0-b2ed6de5a72c.jpg)  
 

类似的，当程序需要写入数据的时候，就会开启一个通向目的地的流。这时候你就可以想象数据好像在这其中“流”动一样。

   ![](http://dl.iteye.com/upload/attachment/0084/1389/ec4635d0-239b-3ccc-806a-1fbf8d5126fc.jpg)

**2.Java流输入输出原理**

Java把不同来源和目标的数据都统一抽象为数据流。

- 输入流: 程序可以从目标数据源中读取数据的流。
- 输出流: 程序能向目标数据源中写入数据的流。

![](http://dl.iteye.com/upload/attachment/0084/1391/04a94356-07d9-3ce0-bf15-39b8dd0a4bb7.jpg)  
 **8.3流的分类**

- 按流向分  
  输入流: 程序可以从中读取数据的流。  
  输出流: 程序能向其中写入数据的流。

![](http://dl.iteye.com/upload/attachment/0084/1393/8f6a5627-05f8-387e-853b-b2715dab3cb6.jpg)  
 

- 按数据传输单位分  
  字节流: 以字节为单位传输数据的流  
  字符流: 以字符为单位传输数据的流

![](http://dl.iteye.com/upload/attachment/0084/1395/14530429-2f57-3e5e-bf69-527127b487e9.jpg)  
 

- 按功能分  
  节点流: 用于直接操作目标设备的流  
  过滤流: 是对一个已存在的流的链接和封装，通过对数据进行处理为程序提供功能强大、灵活的读写功能。

![](http://dl.iteye.com/upload/attachment/0084/1398/13eedeca-3a1d-343a-83aa-9e683e994dd2.jpg)  
 **3.1字节流和字符流**

JDK中与流相关的类和接口都位于java.io包中

- 字节流：字节流以字节（8bit）为单位
- 字符流：字符流以字符为单位，对字符进行高效操作的流对象。本质其实就是基于字节流读取时，去查了指定的码表。

字节流和字符流的区别：

- 读写单位不同：字节流以字节（8bit）为单位，字符流以字符为单位，根据码表映射字符，一次可能读多个字节。
- 处理对象不同：字节流能处理所有类型的数据（如图片、avi等），而字符流只能处理字符类型的数据。

**结论：只要是处理纯文本数据，就优先考虑使用字符流。 除此之外都使用字节流。**

 

流涉及相关的类：

![](http://dl.iteye.com/upload/attachment/0084/1404/f4c02104-a5fc-32c1-89e8-bd7ecda610fd.jpg)  
 

 **3.1.1字节流：**

![](http://dl.iteye.com/upload/attachment/0084/1406/7b51a40b-5e6f-3f58-8293-9e1a1796a489.jpg)  
 

输入字节流InputStream主要方法  
 

- //读取一个字节并以整数的形式返回(0~255),  
   //如果返回-1已到输入流的末尾。  
  int read() throws IOException
- //读取一系列字节并存储到一个数组buffer，  
   //返回实际读取的字节数，如果读取前已到输入流的末尾返回-1  
  int read(byte\[] buffer) throws IOException
- //读取length个字节  
   //并存储到一个字节数组buffer，从off位置开始存,len为要读取的最大字节数  
   //返回实际读取的字节数，如果读取前以到输入流的末尾返回-1  
  int read(byte\[] buffer, int off, int len)throws IOException
- //关闭流释放内存资源  
  void close() throws IOException

TestFileInputStream.java

```
/**
 * 将TestFileInputStream.java中的内容读出来
 * @author Administrator
 *
 */
public class TestFileInputStream {
	public static void main(String[] args) {
		FileInputStream in = null;
		try {
			in = new FileInputStream("D:\\TestFileInputStream.java");
		} catch (FileNotFoundException e) {
			System.out.println("没有找到TestFileInputStream.java文件");
			e.printStackTrace();
			return;
		}
		//如果流不为空循环流
		if(in!=null){
			StringBuffer buffer = new StringBuffer();
			byte b[] = new byte[1024];
			try {
				while (in.read(b)!=-1) {
					buffer.append(new String(b));
					b = new byte[1024];
				}
				System.out.println(buffer.toString());
			} catch (IOException e) {
				System.out.println("读取错误");
				e.printStackTrace();
				return;
				//关闭流
			}finally{
				if(in!=null){
					try {
						in.close();
						in = null;
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
```

 输出字节流OutputStream主要方法

 

- //向输出流中写入一个字节数据,该字节数据为参数b的低8位  
  void write(int b) throws IOException
- //将一个字节类型的数组中的数据写入输出流  
  void write(byte\[] b) throws IOException
- //将一个字节类型的数组中的从指定位置（off）开始的  
   //len个字节写入到输出流  
  void write(byte\[] b, int off, int len)throws IOException
- //关闭流释放内存资源  
  void close() throws IOException
- //将输出流中缓冲的数据全部写出到目的地  
  void flush() throws IOException
- 先flush(),再close()

TestFileOutputStream

```
/**
 * 将TestFileInputStream.java中的内容读出来然后写入到TestFileInputStream2.java
 * 
 * @author Administrator
 * 
 */
public class TestFileOutputStream {
	public static void main(String[] args) {
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new FileInputStream("D:\\TestFileInputStream.java");
			out = new FileOutputStream("D:\\TestFileInputStream2.java");
			if(in!=null){
				StringBuffer buffer = new StringBuffer();
				byte b[] = new byte[1];
				while (in.read(b)!=-1) {
					buffer.append(new String(b));
					out.write(b);
					b = new byte[1];
				}
			}
		} catch (FileNotFoundException e) {
			System.out.println("没有找到TestFileInputStream.java文件");
			e.printStackTrace();
			return;
		} catch (IOException e) {
			System.out.println("读取或写入发生错误");
			e.printStackTrace();
		}finally {
		  	try {
		  		if(in != null) {
		  			in.close(); 
		  			in = null;
		  		}
		    } catch(IOException e) {
		    	e.printStackTrace();
		    }
		  	try {
		  		if(out != null) {
		  			out.flush();
		    		out.close();
		    		out = null;
		    	} 
		    } catch(IOException e) {
		    	e.printStackTrace();
		    }
		  }
	}
}
```

 **3.1.2字符流**

   
![](http://dl.iteye.com/upload/attachment/0084/1410/493924de-9f2b-3ba1-81b6-cec48b65a51e.jpg)  
 

输入字符流Reader主要方法

 

- //读取一个字符并以整数的形式返回(0~255),如果返回-1已到输入流的末尾。  
  int read() throws IOException
- //读取一系列字符并存储到一个数组buffer，  
   //返回实际读取的字符数，如果读取前已到输入流的末尾返回-1  
  int read(char\[] cbuf) throws IOException
- //读取length个字符  
   //并存储到一个数组buffer，从off位置开始存,最多读取len  
   //返回实际读取的字符数，如果读取前以到输入流的末尾返回-1  
  int read(char\[] cbuf, int off, int len)throws IOException
- //关闭流释放内存资源  
  void close() throws IOException

 TestFileReader

```
package javaio.reader;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * 读取指定文件内容
 * 
 * @author Administrator
 * 
 */
public class TestFileReader {
	public static void main(String[] args) {
		FileReader reader = null;
		try {
			reader = new FileReader("D:\\TestFileReader.java");
			if(reader!=null){
				StringBuffer buffer = new StringBuffer();
				char b[] = new char[1024];
				while (reader.read(b)!=-1) {
					buffer.append(new String(b));
					b = new char[1024];
				}
				System.out.println(buffer.toString());
			}
		} catch (FileNotFoundException e) {
			System.out.println("没有找到TestFileReader.java文件");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(reader != null) {
				try{
					reader.close();
				}
				catch (IOException e){
					e.printStackTrace();
				}
				reader = null;
			}
		}
	}
}
```

 

输出字符流Writer

TestFileWriter

```
package javaio.writer;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
 * 将TestFileReader.java内容写入到TestFileReader2.java中
 * @author Administrator
 *
 */
public class TestFileWriter {
	public static void main(String[] args) {
		FileReader reader = null;
		FileWriter writer = null;
		try {
			reader = new FileReader("D:\\TestFileReader.java");
			writer = new FileWriter("D:\\TestFileReader2.java");
			if(reader!=null){
				char b[] = new char[1];
				while (reader.read(b)!=-1) {
					writer.write(b);
				}
			}
		} catch (FileNotFoundException e) {
			System.out.println("没有找到TestFileReader.java文件");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(reader != null) {
				try{
					reader.close();
				}
				catch (IOException e){
					e.printStackTrace();
				}
				reader = null;
			}
			if(writer != null) {
				try{
					writer.flush();
					writer.close();
				}
				catch (IOException e){
					e.printStackTrace();
				}
				writer = null;
			}
		}
	}
}
```

 未完续……