转换流
就是进行字节流和字符流之间转换的
InputStreamReader: 是字节流通向字符流的桥梁
OutputStreamWriter: 是字符流通向字节流的桥梁
1.创建读和写的流对象,可以指定编码,不指定默认是utf-8
InputStreamReader(InputStream in)
InputStreamReader(InputStream in, String charsetName)
OutputStreamWriter(OutputStream out)
OutputStreamWriter(OutputStream out, String charsetName)
2.进行读和写的操作
读: read(char[] cbuf)
写: write(String str)
3.关流,释放资源
close()
但是在jdk11之后就没必要了,因为字符流会自己转换
对象操作流
对象的序列化
将内存中的对象写入到本地文件中,直接打开文件是读不懂的
对象的反序列化
将文件中保存的对象数据读取到内存中
对象操作流的分类
// Serializable接口的意义:
// 称之为是一个标记性接口,里面没有任何的抽象方法。只要一个类实现了这个Serizalizable接口,那么就表示这个类的对象可以被序列化
public class User implements Serializable {
序列化流
User user = new User("zhangsan","qwer");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("day14\\a.txt"));
oos.writeObject(user);
oos.close();
反序列化流
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("day14\\a.txt"));
User o = (User) ois.readObject();
System.out.println(o);
ois.close();
public class User implements Serializable {
private static final long serialVersionUID = 1L; //加了这个可以保证修改类之后序列化不变
private String username;
private transient String password; //加了这个可以让这个值不被序列化
public String getUsername() {
return username;
}
对象输入输出流的批量操作
public static void main(String[] args) throws IOException, ClassNotFoundException {
Student s1 =new Student("杜紫藤","16");
Student s2 =new Student("张三","25");
Student s3 =new Student("李四","22");
Student s4 =new Student("王五","23");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("day14\\a.txt"));
// oos.writeObject(s1);
// oos.writeObject(s2);
// oos.writeObject(s3);
// oos.writeObject(s4);
ArrayList<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
oos.writeObject(list);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("day14\\a.txt"));
ArrayList<Student> list2 = (ArrayList<Student>)ois.readObject();
for (Student student : list2) {
System.out.println(student);
}
// while(true){
// try {
// Object o = ois.readObject();
// System.out.println(o);
// } catch (EOFException e) {
// break;
// } catch (ClassNotFoundException e) {
//
// throw new RuntimeException(e);
// }
//
// }
ois.close();
}