1.Stream流
在容器A,B中,若想将两个容器中的物质发生交换,一般需要一个介质或者是载体,充当二者的桥梁。而JAVA中,想要实现磁盘和JVM内存中数据的通信则引入了Stream流,输入流为in,输出流为out
2.流的分类
按数据流向可分为输入流和输出流,按操作单位可分为字节流和字符流,字符流只适合操作文本,
3.流的使用
package cn.tedu;
import java.io.*;
public class TestStream {
public static void main(String[] args) {
method1();
method2();
method3();
method4();
}
//字符流
private static void method1() {
//字符输入流
Reader in = null;
//字符输出流
// Writer out = new BufferedWriter(new FileWriter(""));
try {
//抽象类无法实例化,创建多态对象
in = new FileReader("D:\\Test\\1.txt");
//通过路径将“流”(管道)插到对于的文件上
//使用缓冲区形成高速流,约快1倍
in = new BufferedReader(new FileReader("D:\\Test\\1.txt"));
int b;
//in.read();//read()方法读取文件,
//每次执行read()方法,下标都会往下移
while ((b=in.read())!= -1){
//read()读取到的是编码表的码值,转为char字符
System.out.println((char) b);
}
} catch (FileNotFoundException e) {//通过路径无法找到文件
e.printStackTrace();
} catch (IOException e) {//
e.printStackTrace();
}finally {
try {
in.close();//每次流使用完毕都都要关闭,避免资源浪费
/**关流是有顺序的:若有多个流,最后创建的流最先关闭,并各自try-catch
* 原因:当在一个try-catch里时,最先关闭的流如果出现错误无法关闭,
* 直接catch后,会造成剩余的流没有关闭,
* 如果嫌finally中关流的try—catch太多可以将关流写为一个方法,依次调用
*/
} catch (IOException e) {
e.printStackTrace();
}
}
}
//字节流
private static void method2() {
//字节输入流
// InputStream in = new BufferedInputStream(new FileInputStream(""));
//字节输出流
OutputStream out = null;
try {
//将流通向指定路径的文件,没有该文件会创建
out = new FileOutputStream("D:\\Test\\2.txt");
//替换写入,原内容清除
out = new BufferedOutputStream
(new FileOutputStream("D:\\Test\\2.txt"));
//追加写入,之前文件中的内容不会清除
out = new BufferedOutputStream
(new FileOutputStream("D:\\Test\\2.txt",true));
out.write(98);//将编码表中的98号元素写入指定路径的文件
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//序列化:将一些数据存储到磁盘中
private static void method3() {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream
(new FileOutputStream("D:\\Test\\123.txt"));
/**一个用来测试序列化的类,
* 使用implements实现Serializable接口(空接口,作为一个注解)
*包含name和age属性和一个构造方法
*/
Person p = new Person("皮皮",18);
oos.writeObject(p);//以字节码的形式存储到指定文件
System.out.println("finish....");
} catch (IOException e) {
System.out.println("defeat....");
e.printStackTrace();
}finally {
try {
oos.close();//关流
} catch (IOException e) {
e.printStackTrace();
}
}
}
//反序列化
private static void method4() {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream
(new FileInputStream("D:\\Test\\123.txt"));
Object o = ois.readObject();//使用readObject()方法反序列化,一次性读完
System.out.println(o.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//关流方法
public <T extends java.io.Closeable> void close(T t) {
try {
if (t != null) {
t.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}