概述
基本概念
- 输入流:从硬盘到内存。(输入又叫做 读 read)
- 输出流:从内存到硬盘。(输出又叫做 写 write)
- 字节流:一次读取一个字节。适合非文本数据,它是万能的,啥都能读。
- 字符流:一次读取一个字符。只适合读取普通文本。
Java 中所有 IO 流中凡是以 Stream 结尾的都是字节流。凡是 Read 和 Writer 结尾的都是字符流。
体系结构
- 四大头领(都是抽象类)
- InputStream
- OutStream
- Reader
- Writer
- File 相关的
- FileInputStream
- FileOutputStream
- FileReader
- FileWriter
- 缓冲流相关的
- BufferedInputStream
- BufferedOutputStream
- BufferedReader
- BufferedWriter
- 转换流相关的
- InputStreamReader
- OutputStreamWriter
- 打印流相关的
- PrintStream
- PirntWriter
- 对象相关的
- ObjectInputStream
- ObjectOutputStream
- 数据类型相关的
- DataInputStream
- DataOutputStream
- 字节数组相关的
- ByteArrayInputStream
- ByteArrayOutputStream
- 压缩解压缩相关的
- GZIPInputStream
- GZIPOutputStream
- 线程相关的
- PipedInputStream
- PipedOutputStream
- 所有的流都实现了 Closeable 接口,都有 close() 方法,流用完要关闭。
- 所有的输出流都实现了 Flushable 接口,都有 flush() 方法,flush 方法的作用是将缓存清空,全部写出。
各种流的详解
文件输入输出流 FileInputStream & FileOutputStream
FileInputStream
-
构造方法之一
FileInputStream (Stirng s)
-
普通方法
read()
返回文件中的第一个字节本身(ascii码),读一次往后移一个字节,如果读不到任何数据就返回 -1read(byte[] b)
一次最多可以读取到 b.length 个字节,返回值是读取到的字节数量,如果每读到任何数据就返回 -1read(byte[] b, int off, int len)
一次最多读 len 个字节,并且从 byte 数组的第 off 位置开始存skip(long n)
跳过流中的 n 个字节后读取available()
返回流中剩余的字节数
FileOutputStream
- 构造方法
FileOutputStream(String name, boolean append)
如果 append == false,则在第一次建立流时将源文件的内容清空
如果 append == true,则通过追加的方式写入 - 普通方法
FileReader & FileWriter 与 FileInputStream & FileOutputStream使用方式类似,只是字符流的使用 char[ ] 存储,还可以直接写入字符串
// FileWriter 测试代码
try (FileWriter fw = new FileWriter("C:\\Users\\win\\Desktop\\111.txt")) {fw.write("hello");fw.write("world", 1, 2);fw.write("hello".toCharArray(), 0, 2);fw.write("hello".toCharArray());} catch (IOException e) {throw new RuntimeException(e);
}
try-with-resource
下面这种形式的流是 try-with-resource 语法,不需要手动写 close() 了,资源会自动关闭。因为所有的流都实现了 Closeable 接口的父接口 AutoCloseable 接口,都可以使用 try-with-resource 语法。
try(流1;流2){操作代码;
}catch(Exception e){}
注:本文章源于学习动力节点老杜
的java教程视频后的笔记整理,方便自己复习的同时,也希望能给csdn的朋友们提供一点帮助。