一.what?(什么是IO流)
Java把不同的输入输出源(键盘、文件、网络文件等)抽象成流的形式,通过流的方式,使得java程序以相同的方式去访问不同的输入输出源,流是输出到输入端的一种有序数据
二.why?(为什么需要IO流)
IO流是输入输出的基础,使得文件的输入输出更加方便操作。
三.how?(怎样使用IO流)
再说怎么样去使用IO流前,我们先讲讲IO流的分类
1.IO流的分类
a.按照流的流向划分,可以分为两类:
输入流:只能从中读数据,不能向其写数据
输出流:只能向其写数据,不能从中读数据。
java输入流主要有InputStream 和Reader作为基类 ,输出流主要有OutputStream和Writer两个基类
b.从操作数据大小划分,也可划分为两类:
字符流:操作最小的单位为16位的基本数据。
字节流:操作最小的单位为8位的基本数据。
b.从流的角色划分,也可划分为两类:
低级流(节点流):直接从soure到sink端的流
高级流(处理流): 对已存在的低级流的一种封装来进行对数据操作。(是一种典型的装饰器的设计模式,有兴趣的同学可以看下)
Java IO流共涉及到40几个类,但是基本上都是从以下四个类派生出来的,字符流:Reader(输入流)、Writer(输出流)字节流:InputStream(输入流)、OutputStream(输出流)。这里仿网上的自己撸了个脑图:
或者按照使用场景划分:
2.常用IO类使用
`这里拿文件流举个简单的例子,其他的使用,请大家查看具体api
private static void WriterFos() {
//字节流写入文件
FileOutputStream fos=null;
File file=new File("a.txt");
try {
fos=new FileOutputStream(file);
fos.write("aa".getBytes());
fos.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//操作结束后 一定要关闭
if(null!=fos) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private static void WriterFileWriter() {
//字符流写入文件
FileWriter fw=null;
File file=new File("b.txt");
try {
fw=new FileWriter(file);
fw.append("b");
fw.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(null!=fw) {
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private static void WriterConvertStream() {
//字符流写入文件
FileOutputStream fos=null;
OutputStreamWriter osw=null;
try {
File file=new File("c.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
fos=new FileOutputStream(file);
// 构建FileOutputStream对象,文件不存在会自动新建
osw=new OutputStreamWriter(fos);//转换流 将输出字节流转成字符输出流
osw.append('c');
osw.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//操作结束后 一定要关闭
if(null!=osw) {
try {
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=fos) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
本文如果不正之处。欢迎大家批评指正。
文末给大家推荐一下这篇博客:https://www.cnblogs.com/skywang12345/p/io_01.html ,这个里面关于IO讲的很全面