---
title: "java输入/输出（io）记录"
author: "天边一朵雲"
date: "2011-08-22T10:56:00Z"
tags: []
categories: ["编程语言"]
slug: "java-io"
draft: false
lastmod: "2012-12-24T10:47:27Z"
id: 1752827
url: "https://itexpress.iteye.com/blog/1752827"
---

分类

字节输入流

字节输出流

字符输入流

字符输出流

抽象基类

*InputStream*

*OutputStream*

*Reader*

*Writer*

访问文件

**FileInputStream**

**FileOutputStream**

**FileReader**

**FileWriter**

访问数组

**ByteArrayInputStream**

**ByteArrayOutputStream**

**CharArrayReader**

**CharArrayWriter**

访问管道

**PipedInputStream**

**PipedOutputStream**

**PipedReader**

**PipedWriter**

访问字符串

**StringReader**

**StringWriter**

缓冲流

BufferedInputStream

BufferedOutputStream

BufferedReader

BufferedWriter

转换流

 

 

InputStreamReader

OutputStreamWriter

对象流

ObjectInputStream

ObjectOutputStream

 

 

抽象基类

*FilterInputStream*

*FilterOutputStream*

*FilterReader*

*FilterWriter*

打印流

 

PrintStream

 

PrintWriter

推回输入流

PushbackInputStream

 

PushbackReader

 

特殊流

DataInputStream

DataOutputStream

 

(斜体为抽象类，蓝色粗体为节点流，红色为处理流)

**I/O不熟悉知识点：**

**File类**

**文件过滤器**

```
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import static java.lang.System.out;

/**
 * ClassName:FilefilterTest	 
 */
public class FilefilterTest {

	public static void main(String[] args) throws IOException {
		//新建一个路径
		File filePath = new File("C:/DOCUME~1/Temp");
		if(filePath.isDirectory()) {
			//调用自定义过滤器
			String[] files = filePath.list(new FileFilter());
			for(String fileName : files) {
				out.println(fileName);
			}
		}

	}
}
/**
 * ClassName:FileFilter
 */
class FileFilter implements FilenameFilter {
	@Override
	public boolean accept(File dir, String name) {
		//设定自定义过滤器的条件  过滤所有非dir路径下的java文件和文件夹
		return name.endsWith(".java") || new File(dir+File.separator+name).isDirectory();
	}
}
```

类似的还有File\[] java.io.File.listFiles(FilenameFilter filter);

节点流&gt;字节流&gt;输入流

```
		File file = new File("F:\\testSource\\FilefilterTest.java");
		/*
		 * 输入流    节点流（InputStream(字节流) Reader（字符流）
		 * 实现类分别为FileInputStream FileReader）
		 */
		FileInputStream fis = new FileInputStream(file);
		byte[] b = new byte[(int) file.length()];
		int readLen = 0;
		if((readLen = fis.read(b))>0) {
			out.println(new String(b,0,readLen));
		}
		fis.close();
```

节点流&gt;字节流&gt;输出流

```
	/**
	 * fileOutput:(从输入字节流中读取数据由输入字节流接收写入到.txt文件)
	 * 文件copy的作用
	 */
	private static void fileOutput() throws IOException{
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try{
			File file = new File("F:\\testSource\\Struts2Test.java");
			fis = new FileInputStream(file);
			byte[] b = new byte[(int) file.length()];
			int readLen = 0;
			if((readLen = fis.read(b))>0) {
				File newFile = new File("F:\\testSource\\newFile.txt");
				if(!newFile.exists()) {
					newFile.createNewFile();
				}
				/*
				 * 输出流    节点流（OutputStream（字节流） Writer（字符流） 
				 * 实现类分别为FileOutputStream FileWriter）
				 */
				fos = new FileOutputStream(newFile);
				//字节流b  如果是Writer可以直接write(String str);
				fos.write(b,0,readLen);
			}
		}catch(FileNotFoundException e1){
			
		}catch(IOException e2){
			
		}finally{
			if(null!=fis)
				fis.close();
			if(null!=fos)
				fos.close();
		}

	}
```

处理流（包装节点流）

```
		//创建字节流
		FileOutputStream fos = new FileOutputStream(new File("F:\\testSource\\newFile2.txt"));
		//转换流包装输出流（将字节流转换成字符流）
		OutputStreamWriter osw = new OutputStreamWriter(fos);
		//向流中写入字符
		osw.write("this ");
		osw.write("is ");
		osw.write("OutputStreamWriter");
		//将流刷入文件
		osw.flush();
		//流关闭
		fos.close();
```

重定向输出流

```
	/**
	 * 重定向输出流
	 * @throws IOException 
	 */
	public static void redirectOutputStream() throws IOException {
		PrintStream ps = null;
		try {
			//新建输出流
			FileOutputStream fos = new FileOutputStream(new File("F:\\testSource\\newFile3.txt"));
			//转换节点流,PrintStream为输出流
			ps = new PrintStream(fos);
			//System重定向输出流（默认为控制台显示器）
			System.setOut(ps);
			out.println("重定向输出流到文件newFile3");
			ps.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally {
			if(ps!=null)
				ps.close();
		}
	}
```

重定向标准输入输出流的方法：System.setErr(PrintStream ps) System.setIn(PrintStream ps) System.setOut(PrintStream ps)

读取进程的输入流

```
	public static void readProcess() throws IOException {
		BufferedReader br = null;
		try {
			//打开计算器
			Process rt = Runtime.getRuntime().exec("calc");
			//将进程的InputStream 包装成转换流，再将转换流包装成缓冲流
			br = new BufferedReader(new InputStreamReader(rt.getInputStream()));
			String str;
			while((str = br.readLine())!=null){
				out.println(str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			if(br != null) {
				br.close();
			}
		} 
	}
```

实现对象序列化

序列化对象

```
import java.io.Serializable;
import lombok.Data;

public @Data class Person implements Serializable{
	private static final long serialVersionUID = 1L;
	private int age;
	private String name;
}
```

这里用到了[lombok](http://projectlombok.googlecode.com/files/lombok.jar)简化了javabean的编写

对象实例化以及读取实例化对象

```
	/**
	 * 实现对象序列化
	 * @throws IOException 
	 */
	public static void objectSerializable() throws IOException {
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;
		try {
			Person person = new Person();
			person.setAge(24);
			person.setName("zpf");
			/*
			 * 创建ObjectOutputStream(对象流)
			 * 把序列化对象输出到File对应的文件中
			 */
			oos = new ObjectOutputStream(new FileOutputStream(new File("F:\\testSource\\newFile4.txt")));
			/*
			 * 调用ObjectOutputStream的writeObject方法把对象写入文件
			 */
			oos.writeObject(person);
			oos.close();
			/*
			 * 读取文本文件序列化后的对象
			 * 创建输入流
			 */
			ois = new ObjectInputStream(new FileInputStream(new File("F:\\testSource\\newFile4.txt")));
			/*
			 * 读取流并转换成对象
			 */
			Person readPerson = (Person)ois.readObject();
			out.println("age:"+readPerson.getAge()+"	name:"+readPerson.getName());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}finally {
			if(null!=oos) {
				oos.close();
			}
			if(ois!=null) {
				ois.close();
			}
		}
	}
```

对象引用序列化：被序列化的非基本类型是可序列化的。代码略.....

 

自定义序列化总结：

1：若序列化对象中有些属性不需要序列化可用关键字transient修饰对象属性

例：

```
Person对象中的name属性可以这样定义：
private transient String name;
```

这样在序列化时就不会序列化name属性（反序列化取不到name属性）。

 

2：需要实现自定义序列化的对象类需要在其中加入三方法：

【1】writeObject(ObjectOutputStream oos)throws IOException {}

【2】readObject(ObjectInputStream ois) throws IOException,ClassNotFoundException {}

【3】readObjectNoData()throws throws ObjectStreamException{}

3：自定义序列化的对象类中重写Object writeReplace()throws ObjectStreamException{}方法（待确认）

这种方法可以把序列化对象类型按照需要转换。

 

转自：[www.itlanguageexpress.info](http://www.itlanguageexpress.info)