IO流简介及常见流操作;
1、IO(Input-Output)流概述:
IO流是用来处理设备之间的数据传输;java对数据的操作是通过流的方式来完成的;
2、常见流操作:
2.1、转换流:字节流与字符流之间转换的桥梁
InputStreamReader --读取字节,并使用指定的字符集将其解码为字符;
OutputStreamWriter--编码;
2.2、序列化和反序列化:将对象数据进行持久化存储;
ObjectOutputStream--序列化:将对象写入文本数据
ObjectInputStream--反序列化:从文本数据中读取数据
注意事项:
a、被序列化的对象必须实现Serializable接口;
b、不需要序列化的数据可以用transient修饰;
c、序列化后,文件数据不能变更,否则会反序列化失败;
// 使用序列化、反序列化存储和调用自定义对象 public class Student implements Serializable { public String name; public int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Student{" + "name=‘" + name + ‘\‘‘ + ", age=" + age + ‘}‘; } } public class demo1 { public static void main(String[] args)throws IOException { // 创建集合存储自定义数据 ArrayList<Student> list = new ArrayList<>(); // 创建学生对象 list.add(new Student("张无忌",20)); list.add(new Student("赵敏",20)); list.add(new Student("周芷若",20)); // 创建序列化对象 ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("day13_7.24\\c.txt")); // 存储数据 o.writeObject(list); // 关闭资源 } } public class demo2 { public static void main(String[] args) throws IOException, ClassNotFoundException { // 创建反序列化对象 ObjectInputStream o = new ObjectInputStream(new FileInputStream("day13_7.24\\c.txt")); // 读取数据 ArrayList<Student> list =(ArrayList<Student>) o.readObject(); System.out.println(list); o.close(); } }
2.3装饰者设计模式:
1、使用环境:
a、在不使用继承、不改变原类的基础上,需要拓展一个类的功能;
2、使用条件:
a、装饰者和被装饰者必须实现相同的接口;
b、装饰者类中必须引入被装饰者类的对象;
c、在装饰类中拓展被装饰者类的功能;
//定义一个接口 public interface Car { public void up(); public void down(); } // 被装饰类 public class A_Car implements Car { @Override public void up() { System.out.println("向上开、、、"); } @Override public void down() { System.out.println("向下开、、、"); } } //装饰类 public class B_Car implements Car { // 传入被装饰者对象 public A_Car a; public B_Car(A_Car a) { this.a = a; } @Override public void up() { a.up(); // 扩展A_Car的功能 System.out.println("向上冲、、、"); } @Override public void down() { } public class test { public static void main(String[] args) { B_Car b = new B_Car(new A_Car()); b.up(); b.down(); } }
3、流的操作规律:
明确操作源和操作目的地
源:BufferedReader、BufferedInputStream(文本文件)、Socket流(网络)、System.in(键盘)
目的:BufferedWriter、BufferedOutputStream(文本文件)、Socket流(网络)、System.out(键盘)
原文:https://www.cnblogs.com/-star/p/13374939.html