Java中的io流学习(了解四大基类和基本步骤)

Java中io流四大基类及io流操作四大基本步骤

io流:(input/output)即输入输出流。面向对象的思想之一是面向接口编程,面向父类编程,也就是多态。所以学好基类(父类)很重要。

分类

  1. 按处理数据类型角度,可分为字节流(例如音频视频等)和字符流(针对纯文本)。
  2. 按数据流向,可分为输入流和输出流(输入输出是对程序来说的)。
  3. 按流的功能,可分为节点流和处理流(没有节点流,处理流发挥不了任何作用),流的名字前面是File或ByteArray开头的均是节点流,其他的是处理流,处理流就是为了提升性能的。

1、四大基类

抽象类名 说明 常用方法
InputStream 字节输入流的父类,数据单位为字节 int read()、void()
OutputStream 字节输出流的父类,数据单位为字节 void write(int)、void flush()、void close()
Reader 字符输入流的父类,数据单位为字符 int read()、void close()
Writer 字符输出流的父类,数据单位为字符 void write(String)、void flush()、void close()

2、io流操作四大步骤

创建源、选择流、操作(读还是写)、释放资源

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class IOSteps {

	public static void main(String[] args) {
		// 1、创建源(F盘下面的io.txt文件里的内容为hello)
		File src = new File("F:/io.txt");
		// 2、选择流(字节输入流)
		InputStream is = null;
		try {
			is = new FileInputStream(src);
			// 3、操作
			int temp = 0;// 读到文件的末尾返回-1
			while ((temp = is.read()) != -1) {
				System.out.print((char) temp);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 4、释放资源(通知操作系统,虚拟机无权释放资源,只是通知操作系统OS)
			try {
				if (is != null) {// 用到了才通知操作系统关闭,加上判断可避免出现空指针异常
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}// main

}

输出结果为:hello
后面还有更简洁的写法(用try-with-resource语法)。

原文地址:https://www.cnblogs.com/zxfei/p/10783313.html