对象流
序列化和反序列化
序列化就是在保存数据时,保存数据的值和数据类型
反序列化就是在恢复数据时,恢复数据的值和数据类型
需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该
类必须实现如下两个接口之一:
Serializable/这是一个标记接口,没有方法
Externalizable/该接口有方法需要实现,因此我们一般实现上面的Serializable接口
package IO;
import org.junit.jupiter.api.Test;
import java.io.*;
/**
* @author 小小小白白白白
*/
public class Oos {
/**
* 序列化保存
*/
@Test
public void ObjectOutputStream() throws Exception {
//它序列化后保存的不是文本的格式,而是它自己的格式
String filepath ="e:\\hello.dat";
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filepath));
oos.writeInt(100);
oos.writeUTF("你好吗");
oos.writeBoolean(false);
//如果要保存一个类,那么该类需要实现Serializable接口
oos.writeObject(new Dog("小黄",2));
oos.close();
}
/**
* 序列化恢复
*/
@Test
public void ObjectInputStream() throws Exception {
//恢复的顺序要和保存的顺序一致
String filepath ="e:\\hello.dat";
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filepath));
System.out.println(ois.readInt());
System.out.println(ois.readUTF());
System.out.println(ois.readBoolean());
Object dog = ois.readObject();
System.out.println(dog);
//如果要使用Dog中的方法需要向下转型(要在同一包内并且该类要位于能够引用到的位置)
//如果在不同的包下需要将该类设为public
Dog dog1=(Dog)dog;
System.out.println(dog1.toString());
ois.close();
}
}
class Dog implements Serializable {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
/**
* 如果之前序列化生成的时候没有toString方法
* 恢复的时候会报错
*/
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
标准输入输出流
转换流-InputStreamReader 和 OutputStreamWriter
当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文
问题,所以建议将字节流转换成字符流可以在使用时指定编码格式(比如utf8,gbk,gb2312,S08859-1等)
public class Input {
public static void main(String[] args) throws IOException {
String filepath="e:\\hello.txt";
//把FileInputStream转成InputStreamReader,并指定其编码格式
InputStreamReader isr = new InputStreamReader(new FileInputStream(filepath),"gbk");
//把InputStreamReader传入BufferedReader
BufferedReader br = new BufferedReader(isr);
//将第一行的内容存入s并输出
String s = br.readLine();
System.out.println(s);
br.close();
}
@Test
public void Output() throws IOException {
String filepath="e:\\hello.txt";
String charset="gbk";
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filepath),charset);
osw.write("梅长苏");
osw.close();
}