流
代表有能力产生数据的数据源对象或者有能力接收数据的接收端对象。
面向字节:
- InputStream
- OutputStream
面向字符:
- Reader
- Writer
InputStream OutputStream 字节流
不同的数据源有不同的InputStream子类与之对应
流 | 作用 |
---|---|
FileInputStream | 从文件中读取信息 |
StringBufferInputStream | 将String转换为InputStream |
SequenceInputStream | 将两个及以上InputStream转换为单一的InputStream |
ByteArrayInputStream | 将内存缓冲区当作InputStream |
PipeInputStream | 实现管道化概念 |
FilterInputStream | 抽象类作为装饰器的接口 |
FilterInputStream
装饰器修改流满足特殊需求
- DataInputStream 与 DataOutputStream搭配使用,按照可移植的方式读取基本数据类型
- BufferedInputStream 防止每次读取缓冲区时都要进行写操作
使用
- 文件字节输出流 向磁盘中写入数据
public static void main(String[] args) throws IOException {
//不存在直接创建
File f = new File("d:/a.txt");
byte[] data = {0,1,2};
FileOutputStream fo = new FileOutputStream(f);
fo.write(data);
fo.close();
//当多级目录不存在会报错
//解决方法→获取父路径 mkdirs
File f2 = new File("d:/a/b/c/a.txt");
File f3 = new File(f2.getParent());
f3.mkdirs();
FileOutputStream fo2 = new FileOutputStream(f2);
fo2.write(data);
fo2.close();
- 文件字节输入流 从磁盘中读数据
public static void main(String[] args) throws IOException {
File f = new File("d:/a/b/c/a.txt");
FileInputStream fi = new FileInputStream(f);
byte[] b = new byte[100];
fi.read(b);
for(byte by:b) {
System.out.println(by);
}
fi.close();
}
- 关闭流的标准方式 finally
https://how2j.cn/k/io/io-closestream/682.html?p=105150
package stream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TestStream {
public static void main(String[] args) {
File f = new File("d:/lol.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] all = new byte[(int) f.length()];
fis.read(all);
for (byte b : all) {
System.out.println(b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 在finally 里关闭流
if (null != fis)
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Writer Reader 字符流
-
字节流与字符流的转换
InputStreamReader把InputStream转换为Reader
OutputStreamWriter把OutputStream转换为Writer -
写入数据
public static void main(String[] args) throws IOException {
File f = new File("d:/a/b/c/a.txt");
File fNew = new File(f.getParent());
fNew.mkdirs();
FileWriter fo2 = new FileWriter(f);
//开始写入
String data = "123zjnhahaha";
fo2.write(data);
fo2.close();
- 读取数据
public static void main(String[] args) throws IOException {
File f = new File("d:/a/b/c/a.txt");
FileReader fi = new FileReader(f);
char[] b = new char[20];
fi.read(b);
for(char c:b) {
System.out.print(c);
}
fi.close();