java -- 缓冲流、转换流、序列化流

锦通  金牌会员 | 2023-4-19 20:19:46 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 930|帖子 930|积分 2790

缓冲流

缓冲流, 也叫高效流, 按照数据类型分类:

  • 字节缓冲流:BufferedInputStream,BufferedOutputStream
  • 字符缓冲流:BufferedReader,BufferedWriter
缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。
字节缓冲流
  1. // 构造方法
  2. public BufferedInputStream(InputStream in)
  3. // 创建一个 新的缓冲输入流
  4. public BufferedOutputStream(OutputStream out)
  5. // 创建一个新的缓冲输出流。
复制代码
  1. // 字节输出缓冲流
  2. OutputStream out = new BufferedOutputStream(new FileOutputStream("FileAndIoStream\\test\\4.txt"));
  3. out.write("hello world\r\n".getBytes());
  4. out.write("hello world\r\n".getBytes());
  5. out.write("hello world\r\n".getBytes());
  6. out.write("hello world\r\n".getBytes());
  7. out.close();
  8. // 字节输入缓冲流
  9. InputStream in = new BufferedInputStream(new FileInputStream("FileAndIoStream\\test\\4.txt"));
  10. byte[] chs = new byte[1024];
  11. int len = 0;
  12. while ((len = in.read(chs)) != -1) {
  13.     System.out.println(new String(chs, 0, len));
  14. }
  15. in.close();
复制代码
字符缓冲流
  1. // 构造方法
  2. public BufferedReader(Reader in)
  3. // 创建一个 新的缓冲输入流
  4. public BufferedWriter(Writer out)
  5. // 创建一个新的缓冲输出流。
复制代码
特有方法

  • BufferedReader:public String readLine(): 读一行文字。
  • BufferedWriter:public void newLine(): 写一行行分隔符,由系统属性定义符号。
  1. BufferedReader bufferedReader = new BufferedReader(new FileReader("FileAndIoStream\\test\\4.txt"));
  2. String line = null;
  3. while ((line = bufferedReader.readLine()) != null) {
  4.     System.out.println(line);
  5. }
  6. bufferedReader.close();
  7. BufferedWriter bw = new BufferedWriter(new FileWriter("FileAndIoStream\\test\\4.txt"));
  8. bw.write("你好");
  9. bw.close();
复制代码
文本排序练习
  1. 3.侍中、侍郎郭攸之、费祎、董允等,此皆良实,志虑忠纯,是以先帝简拔以遗陛下。愚以为宫中之事,事无大小,悉以咨之,然后施行,必得裨补阙漏,有所广益。
  2. 8.愿陛下托臣以讨贼兴复之效,不效,则治臣之罪,以告先帝之灵。若无兴德之言,则责攸之、祎、允等之慢,以彰其咎;陛下亦宜自谋,以咨诹善道,察纳雅言,深追先帝遗诏,臣不胜受恩感激。
  3. 4.将军向宠,性行淑均,晓畅军事,试用之于昔日,先帝称之曰能,是以众议举宠为督。愚以为营中之事,悉以咨之,必能使行阵和睦,优劣得所。
  4. 2.宫中府中,俱为一体,陟罚臧否,不宜异同。若有作奸犯科及为忠善者,宜付有司论其刑赏,以昭陛下平明之理,不宜偏私,使内外异法也。
  5. 1.先帝创业未半而中道崩殂,今天下三分,益州疲弊,此诚危急存亡之秋也。然侍卫之臣不懈于内,忠志之士忘身于外者,盖追先帝之殊遇,欲报之于陛下也。诚宜开张圣听,以光先帝遗德,恢弘志士之气,不宜妄自菲薄,引喻失义,以塞忠谏之路也。
  6. 9.今当远离,临表涕零,不知所言。
  7. 6.臣本布衣,躬耕于南阳,苟全性命于乱世,不求闻达于诸侯。先帝不以臣卑鄙,猥自枉屈,三顾臣于草庐之中,咨臣以当世之事,由是感激,遂许先帝以驱驰。后值倾覆,受任于败军之际,奉命于危难之间,尔来二十有一年矣。
  8. 7.先帝知臣谨慎,故临崩寄臣以大事也。受命以来,夙夜忧叹,恐付托不效,以伤先帝之明,故五月渡泸,深入不毛。今南方已定,兵甲已足,当奖率三军,北定中原,庶竭驽钝,攘除奸凶,兴复汉室,还于旧都。此臣所以报先帝而忠陛下之职分也。至于斟酌损益,进尽忠言,则攸之、祎、允之任也。
  9. 5.亲贤臣,远小人,此先汉所以兴隆也;亲小人,远贤臣,此后汉所以倾颓也。先帝在时,每与臣论此事,未尝不叹息痛恨于桓、灵也。侍中、尚书、长史、参军,此悉贞良死节之臣,愿陛下亲之信之,则汉室之隆,可计日而待也。
复制代码
  1. public class test {
  2.     public static void main(String[] args) throws IOException {
  3.         BufferedReader br = new BufferedReader(new FileReader("FileAndIoStream\\test\\csb"));
  4.         TreeSet<String> set = new TreeSet<>(new Comparator<String>() {
  5.             @Override
  6.             public int compare(String o1, String o2) {
  7.                 String num1 = o1.split("\\.")[0];
  8.                 String num2 = o2.split("\\.")[0];
  9.                 return Integer.parseInt(num1) - Integer.parseInt(num2);
  10.             }
  11.         });
  12.         String line = null;
  13.         while ((line = br.readLine()) != null) {
  14.             set.add(line);
  15.         }
  16.         br.close();
  17.         BufferedWriter bw = new BufferedWriter(new FileWriter("FileAndIoStream\\test\\csb"));
  18.         for (String s : set) {
  19.             bw.write(s);
  20.             bw.newLine();
  21.             bw.flush();
  22.         }
  23.         bw.close();
  24.     }
  25.     public static void mapToSort() throws IOException {
  26.         BufferedReader br = new BufferedReader(new FileReader("FileAndIoStream\\test\\csb"));
  27.         TreeMap<Integer, String> map = new TreeMap<>();
  28.         String line = null;
  29.         while ((line = br.readLine()) != null) {
  30.             String[] split = line.split("\\.");
  31.             map.put(Integer.parseInt(split[0]), line);
  32.         }
  33.         br.close();
  34.         BufferedWriter bw = new BufferedWriter(new FileWriter("FileAndIoStream\\test\\csb"));
  35.         for (Integer integer : map.keySet()) {
  36.             bw.write(map.get(integer));
  37.             bw.newLine();
  38.             bw.flush();
  39.         }
  40.         bw.close();
  41.     }
  42. }
复制代码
转换流

由于 FileReader 和 FileWriter 无法指定编码 仅可使用平台默认编码 因此若读取/写入其他编码文件会乱码
  1. // java.io.InputStreamReader
  2. // 构造方法
  3. public InputStreamReader(InputStream in, String charsetName)
  4.     String charsetName 指定字符集, 不区分大小写
  5. // java.io.OutputStreamWriter
  6. // 构造方法
  7. public InputStreamReader(OutputStream in, String charsetName)
  8.     String charsetName 指定字符集, 不区分大小写
复制代码
  1. Reader r = new InputStreamReader(new FileInputStream("FileAndIoStream\\test\\csbGBK.txt"), "gbk");
  2. char[] chs = new char[1024];
  3. int len = 0;
  4. while ((len = r.read(chs)) != -1) {
  5.     System.out.println(new String(chs, 0, len));
  6. }
  7. r.close();
  8. Writer w = new OutputStreamWriter(new FileOutputStream("FileAndIoStream\\test\\csbGBK.txt",true), "gbk");
  9. w.write("\n11.END");
  10. w.close();
复制代码
练习

复制文件并转换编码
  1. Reader reader = new InputStreamReader(new FileInputStream("FileAndIoStream\\test\\csbGBK.txt"),"gbk");
  2. Writer writer = new OutputStreamWriter(new FileOutputStream("FileAndIoStream\\test\\csbUTF8.txt"));
  3. char[] chars = new char[1024];
  4. len = 0;
  5. while ((len = reader.read(chars)) != -1) {
  6.     writer.write(new String(chars, 0, len));
  7.     writer.flush();
  8. }
  9. reader.close();
  10. writer.close();
复制代码
序列化

Java 提供了一种对象序列化的机制。用一个字节序列可以表示一个对象,该字节序列包含该对象的数据、对象的类型和对象中存储的属性等信息。字节序列写出到文件之后,相当于文件中持久保存了一个对象的信息。
反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反序列化。对象的数据、对象的类型和对象中存储的数据信息,都可以用来在内存中创建对象。

  • java.io.ObjectOutputStream 类,将Java对象的原始数据类型写出到文件,实现对象的持久存储。
  • java.io.ObjectInputStream 反序列化流,将之前使用ObjectOutputStream序列化的原始数据恢复为对象
  1. // 构造方法
  2. public ObjectOutputStream(OutputStream out)
  3. // 创建一个指定OutputStream的ObjectOutputStream
  4. public ObjectInputStream(InputStream in)
  5. // 创建一个指定InputStream的ObjectInputStream
复制代码
  1. public class Demo {
  2.     public static void main(String[] args) throws IOException, ClassNotFoundException {
  3.         writeObject();
  4.         readerObject();
  5.     }
  6.     // 序列化
  7.     public static void writeObject() throws IOException {
  8.         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("FileAndIoStream\\test\\Person.txt"));
  9.         // 序列化单个对象
  10.         // oos.writeObject(new Person("张三", 17, 1));
  11.         // 序列化多个对象
  12.         List<Person> list = new ArrayList<Person>();
  13.         list.add(new Person("张三",11,1));
  14.         list.add(new Person("李四",15,0));
  15.         list.add(new Person("王五",17,1));
  16.         list.add(new Person("刘六",10,0));
  17.         oos.writeObject(list);
  18.         oos.close();
  19.     }
  20.     // 反序列化
  21.     public static void readerObject() throws IOException, ClassNotFoundException {
  22.         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("FileAndIoStream\\test\\Person.txt"));
  23.         // 反序列化单个对象
  24.         // Person p = (Person) ois.readObject();
  25.         // System.out.println(p);
  26.         // 反序列化多个对象
  27.         Object obj = ois.readObject();
  28.         List<Person> list = (List<Person>) obj;
  29.         for (Person person : list) {
  30.             System.out.println(person);
  31.         }
  32.         ois.close();
  33.     }
  34. }
  35. class Person implements Serializable {
  36.     // 静态内容不能序列化
  37.     private static String className;
  38.     private String name;
  39.     private int age;
  40.     // transient 关键字 瞬态, 不可被序列化
  41.     private transient int sex;
  42.     private static final long serialVersionUID = 1L;
  43.     // 反序列化 不调用构造方法
  44.     public Person() {}
  45.     public Person(String name, int age) {
  46.         this.name = name;
  47.         this.age = age;
  48.     }
  49.     public Person(String name, int age, int sex) {
  50.         this.name = name;
  51.         this.age = age;
  52.         this.sex = sex;
  53.     }
  54.     public String getName() {
  55.         return name;
  56.     }
  57.     public void setName(String name) {
  58.         this.name = name;
  59.     }
  60.     public int getAge() {
  61.         return age;
  62.     }
  63.     public void setAge(int age) {
  64.         this.age = age;
  65.     }
  66.     @Override
  67.     public String toString() {
  68.         return "Person{" +
  69.                 "name='" + name + '\'' +
  70.                 ", age=" + age +
  71.                 ", sex=" + sex +
  72.                 '}';
  73.     }
  74. }
复制代码
反序列化时, 若找不到class文件, 则反序列话失败, 抛出异常 ClassNotFoundException
当jvm反序列化对象时, 能找到class文件, 但在序列化对象后class文件发生了改变, 则反序列化失败, 抛出异常 InvalidClassException
当类作为Serializable 的实现类初始化时, 会同时生成一个序列号, 反序列化时检测到序列号不一致
打印流

平时我们在控制台打印输出,是调用print方法和println方法完成的,这两个方法都来自于java.io.PrintStream类,该类能够方便地打印各种数据类型的值,是一种便捷的输出方式
PrintStream类

public PrintStream(String fileName)  : 使用指定的文件名创建一个新的打印流。
  1. public class Demo {
  2.     public static void main(String[] args) throws IOException {
  3.         PrintWriter p = new PrintWriter("FileAndIoStream\\test\\print1.txt");
  4.         p.print("abc");
  5.         p. println(10);
  6.         p.println(true);
  7.         p.close();
  8.         PrintWriter pw = new PrintWriter(new FileWriter("FileAndIoStream\\test\\print2.txt"),true);
  9.         pw.println("你好");
  10.         // 设置输出位置, 将 输出到控制台 改为 输出到文件
  11.         System.setOut(new PrintStream(new FileOutputStream("FileAndIoStream\\test\\print2.txt", true)));
  12.         System.out.println("输出到文件1");
  13.         System.out.println("输出到文件2");
  14.         pw.close();
  15.     }
  16. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

锦通

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表