---
title: "I/O体系结构总结"
author: "raidyue"
date: "2012-07-16T21:22:01Z"
tags: []
categories: ["非技术"]
slug: "i-o"
draft: false
lastmod: "2012-07-16T23:06:43Z"
id: 1595690
url: "https://raidyue.iteye.com/blog/1595690"
---

I/O体系结构总结

流的概念和分类： java类库中的I/O类分为输入和输出连个部分，并将其抽象为“流(stream)”，他代表任何有能力产生产生数据的数据源对象或者是有能力接收数据的接收对象，形象的说流像一根水管，将数据从一头，传到另一头。

流按方向分可分为：输入流和输出流。

按性质分可以分为：原始流InputStream和OutputStream，缓冲流BufferedInputStream和BufferedOutputStream，基于具体数据的流DataInputStream/DataOutputStream，基于对象读写的流ObjectInput/ObjectOutput.

按操作数据分可分为:字节流和字符流

InputStream/OutputStream及其子类：

InputStream/OutputStream是基于字节的（一个byte一个byte的读取）抽象类，因此InputStream/OutputStream无法创建实例对象，因此我们要使用其子类来创建对象，我们常用的其子类，如FileInputStream/FileOutputStream，我们用这两个类从文件中读取或者输出子类，由于可能会抛出异常，我们用……try{}catch{}……处理，，代码实列

```
	/**
```

```
 	* FileOutputStream/FileInputStream
	 * 
	 * @param fileNam
	 *            :文件名
	 * @return:读到的内容作为字符串返回
	 * @throws IOException可能会抛出IO异常
	 */
	public void readAndWrite(String fileName, String newFileName) {

		try {
			// 构造输出流对象，作为一个InputStream对象
			// 创建的对象是InputStream的子类，我们使用父类的变量引用，方便统一使用
			InputStream is = new FileInputStream(fileName);
			OutputStream os = new FileOutputStream(newFileName);
			// 根据流中的字节长度，创建一个byte数组，保存读取到的数据

			// 将流中读取的数据写入另一文件
			int i = 0;
			//如果没有读到末尾,一边读取一边写入
			while ((i = is.read()) != -1) {
				os.write(i);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		is.close();
		os.close();

	}
```

 

 注意：当我们使用完流以后，流并不会自动关闭，而是需要我们手动关闭，在其未关闭时，会一直占用系统资源，就像我们用完水，应该随手关掉水龙头，所以在这里我们也应该关闭流.关闭最上层的流，下层的流也会关闭

 

缓冲流（BufferedInputStream/BufferedOutputStream）:

这连个流分别是InputStream/OutputStream的子类，其用法与上述类似，

public void readAndWrite\_buffered(String filePath, String newFilePath) {

```
		// 创建从源文件来的输入流

		try {
			// 创建源文件的输出流
			InputStream is = new FileInputStream(filePath);
			BufferedInputStream bis = new BufferedInputStream(is);
			// 创建源文件的输入流
			OutputStream os = new FileOutputStream(newFilePath);
			BufferedOutputStream bos = new BufferedOutputStream(os);

			int i = 0;
			while ((i = bis.read()) != -1) {
				bos.write(i);
			}
			is.close();
			os.flush();
			os.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
```

 

上述两种的区别：jvm在计算机内存开辟了专门的区域，

 

当使用第一种方法对文件进行读写时，流的流向是，硬盘某一块空间--&gt;计算机内存--&gt;jvm内存--&gt;计算机内存--&gt;硬盘的另一空间；

使用的耳中方法时会在jvm内存中开辟一小块空间，硬盘某一块空间--&gt;计算机内存--&gt;jvm内存--&gt;缓冲流空间--&gt;vm内存--&gt;计算机内存--&gt;硬盘的另一空间;

缓冲流提高了文件读写的效率，因为如果没有缓冲区，应用程序每次IO都要和设备进行通信，效率很低，因此缓冲区为了提高效率，当写入设备时，先写入缓冲区，等到缓冲区有足够多的数据时，就整体写入设备。

关于DateInputStream和DataOutputStream：

这两种刘只要用来读写指定的数据类型，具体用法与上述类相似。

画板数据保存：

画板保存将在画板总结中详细说明