zoukankan      html  css  js  c++  java
  • 黑马程序员-IO流(对象序列化、RandomAccessFile 类、字符编码、综合练习)

    一、对象序列化

    ObjectOutputStram和ObjectInputStream

    1、概述:

    将堆内存中的对象存入硬盘,保留对象中的数据,称之为对象的持久化(或序列化)

    2、特有方法:

        write(int val)   --->  写入一个字节(最低八位)
        writeInt(int vale)  --->   写入一个32位int值

    3、使用步骤:


    (1)写入流对象:

    1)创建对象写入流,与文件关联,即传入目的
    2)通过写入writeObject()方法,将对象作为参数传入,即可写入文件

    (2)读取流对象

    1)创建对象读取流,与文件关联,即传入源
    2)通过writeObject()方法,读取文件中的对象,并返回这个对象

    4、说明:serialVersion

    a、给类一个可被编译器识别的的序列号,在编译类时,会分配一个long型UID,通过序列号,将类存入硬盘中,并序列化,即持久化。序列号根据成员算出的。静态不能被序列化。如果非静态成员也无需序列化,可以用transien修饰。
    代码示例:

    b、接口Serializable中没有方法,称之为标记接口

    5、代码示例:

    1. import java.io.*;  
    2.   
    3. //创建Person类,实现序列化    
    4. class Person implements Serializable {  
    5.     // 定义自身的序列化方式  
    6.     public static final long serialVersionUID = 42L;  
    7.     // 定义私有属性  
    8.     private String name;  
    9.     private int age;  
    10.     transient String id;  
    11.     String country = "cn";  
    12.   
    13.     // 构造Person类  
    14.     Person(String name, int age, String id, String country) {  
    15.         this.name = name;  
    16.         this.age = age;  
    17.         this.id = id;  
    18.         this.country = country;  
    19.     }  
    20.   
    21.     // 覆写toString方法  
    22.     public String toString() {  
    23.         return name + ":" + age + ":" + id + ":" + country;  
    24.     }  
    25. }  
    26.   
    27. // 对象序列化测试  
    28. class ObjectStreamDemo {  
    29.     public static void main(String[] args) {  
    30.         // 对象写入流  
    31.         writeObj();  
    32.         // 对象读取流  
    33.         readObj();  
    34.     }  
    35.   
    36.     // 定义对象读取流  
    37.     public static void readObj() {  
    38.         ObjectInputStream ois = null;  
    39.         try {  
    40.             // 创建对象读取流  
    41.             ois = new ObjectInputStream(new FileInputStream("obj.txt"));  
    42.             // 通过读取文件数据,返回对象  
    43.             Person p = (Person) ois.readObject();  
    44.             System.out.println(p);  
    45.         } catch (Exception e) {  
    46.             throw new RuntimeException("写入文件失败");  
    47.         }  
    48.         // 最终关闭流对象  
    49.         finally {  
    50.             try {  
    51.                 if (ois != null)  
    52.                     ois.close();  
    53.             } catch (IOException e) {  
    54.                 throw new RuntimeException("写入流关闭失败");  
    55.             }  
    56.         }  
    57.     }  
    58.   
    59.     // 定义对象写入流  
    60.     public static void writeObj() {  
    61.         ObjectOutputStream oos = null;  
    62.         try {  
    63.             // 创建对象写入流  
    64.             oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));  
    65.             // 写入对象数据  
    66.             oos.writeObject(new Person("lisi"25"01""cn"));  
    67.         } catch (Exception e) {  
    68.             throw new RuntimeException("写入文件失败");  
    69.         }  
    70.         // 关闭流资源  
    71.         finally {  
    72.             try {  
    73.                 if (oos != null)  
    74.                     oos.close();  
    75.             } catch (IOException e) {  
    76.                 throw new RuntimeException("写入流关闭失败");  
    77.             }  
    78.         }  
    79.     }  
    80. }  



    二、RandomAccessFile 类(重要!!!)



    1、概述:



    (1)自身具备读写方法(很牛逼!又可以读又可以写)
    (2)通过skipByte(int x)和seek(int x)来达到随机访问文件
    (3)该类不是IO体系子类,而是直接继承Object,但它是IO包中的成员,因为它具备读写方法
    (4)该类内部封装了数组,而且通过指针对数组的元素进行操作,可以通过getFilePoint获取指针位置,同时可以通过seek改变指针位置
    (5)该类可以完成读写的原理是:内部封装了字节输入输出流
    (6)构造函数:RandomAccessFile(File file,String mode),RandomAccessFile(String name, String mode),可已从它的构造函数中看出,该类只能操作文件(也有字符串),而且操作文件还有模式。
              模式传入值:”r“:以只读方式打开;”rw“:打开以便读写
              如果模式为只读,则不会创建文件,会去读一个已存在的文件,若文件不存在,则会出现异常,如果模式为rw,且该对象的构造函数要操作的文件不存在,会自动创建,如果存在,则不会覆盖,也可通过seek方法修改。
    (7)可用于多线程分段写入,即:下载原理

    2、特有方法:

    (1)seek(int n):设置指针,可以将指针设置到前面或后面
    (2)skipBytes(int n):跳过指定字节数,不可往前跳

    3、使用步骤:

    (1)创建RandomAccessFile对象
    (2)将数据写入到指定文件中
    (3)读取数据,读入到指定文件中

    注意:要读取后面的数据,需要调用数组指针,通过改变角标位置,取出相应的数据,即:
               a.调整对象的指针:seek()
               b.跳过指定字节数

    4、代码示例:

    1. import java.io.*;  
    2.   
    3. //注:这几个函数内部都需要try,为测试,在函数上抛异常    
    4. class RanAccFileDemo {  
    5.     public static void main(String[] args) throws IOException {  
    6.         // readRaf();  
    7.         readRaf2();  
    8.         // writeRaf();  
    9.     }  
    10.   
    11.     // 写入数据  
    12.     public static void writeRaf() throws IOException {  
    13.         // 创建对象,写入数据  
    14.         RandomAccessFile raf = new RandomAccessFile("ran.txt""rw");  
    15.         raf.write("王五".getBytes());  
    16.         raf.writeInt(99);  
    17.         raf.write("李四".getBytes());  
    18.         raf.writeInt(97);  
    19.         raf.close();  
    20.     }  
    21.   
    22.     // 读取数据  
    23.     public static void readRaf() throws IOException {  
    24.         // 创建对象,读取数据  
    25.         RandomAccessFile raf = new RandomAccessFile("ran.txt""r");  
    26.         byte[] b = new byte[4];  
    27.         raf.read(b);  
    28.         String name = new String(b);  
    29.         int age = raf.readInt();  
    30.         System.out.println("name=" + name);  
    31.         System.out.println("age=" + age);  
    32.         raf.close();  
    33.     }  
    34.   
    35.     // 读取数据  
    36.     public static void readRaf2() throws IOException {  
    37.         // 创建对象,读取数据  
    38.         RandomAccessFile raf = new RandomAccessFile("ran.txt""r");  
    39.         // 调整对象中的指针  
    40.         // raf.seek(8);  
    41.         // 跳过指定字节数  
    42.         raf.skipBytes(8);  
    43.         byte[] b = new byte[4];  
    44.         raf.read(b);  
    45.         String name = new String(b);  
    46.         int age = raf.readInt();  
    47.         System.out.println("name=" + name);  
    48.         System.out.println("age=" + age);  
    49.         raf.close();  
    50.     }  
    51. }  


    三、字符编码


    1、概述:

    (1)字符流的出现为了方便操作字符,更重要的是加入了编码的转换,即转换流。
    (2)通过子类进行转换
    (3)在两个对象进行构造时,可加入编码表
    (4)可传入编码表的有:
             1)转换流:InuputStreamReader和OutputStreamWriter
             2)打印流:PrintStream和PrintWriter,只有输出流
    (5)常见的编码表:
    1)ASCII:美国标准信息交换码表。用一个字节的7位表示
    2)IOS8859-1:拉丁码表;欧洲码表。用一个字节的8位表示
    3)GB2312:中国的中文编码表
    4)GBK:中国的中文编码表升级,融合了更多的中文文字字符。打头的是两个高位为1的两个字节编码。为负数
    5)Unicode:国际标准码,融合了多种文字
    6)UTF-8:最多用三个字节表示一个字符的编码表,包括:一位、两位、三位表示的字符
          UTF-8有自己的字节码:
          一个字节:0开头
          两个字节:字节一  ---> 110     位数:10 ~ 6
                              字节二  --->  10      位数:5 ~ 0
          三个字节:字节一  ---> 110     位数:15 ~ 12
                              字节二  --->  10      位数:11 ~ 6
                              字节三 --->  10       位数:5 ~ 0

    2、编码和解码

    (1)编码和解码:

    1)编码:字符串变成字节数组
    2)解码:字节数组变成字符串

    (2)转换:

    1)默认字符集:
          String  --->  byte[]   :srt.getBytes()
          byte[]   --->  String  :ne编码w String(byte[])

    2)指定字符集:
          String  --->  byte[]   :srt.getBytes(charsetName)
          byte[]   --->  String  :new String(byte[],charsetName)

    (3)对于编码和解码的字符集转换

    1)如果编码失败,解码就没意义了。
    2)如果编码成功,解码出来的是乱码,,则需对乱码通过再次编码(用解错码的编码表),然后再通过正确的编码表解码。针对于IOS8859-1是通用的。
    3)如果用的是GBK编码,UTF-8解码,那么再通过2的方式,就不能成功了,因为UTF-8也支持中文,在UTF-8解的时候,会将对应的字节数改变,所以不会成功。




    (4)特别注意:

    对于中文的”联通“,这两个字比较特别,它的二进制位正好是和在UTF-8中两个字节打头的相同,可以找到对应的符号,但不再是”联通“了。

    3、代码示例:

    1. import java.util.*;  
    2.   
    3. class EncodeDemo {  
    4.     public static void main(String[] args) throws Exception {  
    5.         CodeDemo();  
    6.         // 编译成功,解码失败后的解决方式  
    7.         CodeBack();  
    8.     }  
    9.   
    10.     public static void CodeDemo() throws Exception {  
    11.         String s = "你好";  
    12.         byte[] b1 = s.getBytes();  
    13.         String s1 = new String(b1);  
    14.         System.out.println(Arrays.toString(b1));  
    15.   
    16.         byte[] b2 = s.getBytes("GBK");// 默认编码  
    17.         String s2 = new String(b2);  
    18.         System.out.println("s1=" + s1 + ",s2=" + s2);  
    19.         System.out.println(Arrays.toString(b2));  
    20.   
    21.         byte[] b3 = s.getBytes("UTF-8");// 国际编码  
    22.         String s3 = new String(b3);  
    23.         System.out.println("s3=" + s3);  
    24.         System.out.println(Arrays.toString(b3));  
    25.   
    26.         byte[] b4 = s.getBytes("ISO8859-1");// 欧洲编码  
    27.         String s4 = new String(b4);  
    28.         System.out.println("s4=" + s4);  
    29.         System.out.println(Arrays.toString(b4));  
    30.     }  
    31.   
    32.     // 编码与解码  
    33.     public static void CodeBack() throws Exception {  
    34.         String s = "你好";  
    35.         System.out.println("原数据:" + s);  
    36.         byte[] b1 = s.getBytes("GBK");// 默认编码  
    37.         System.out.println(Arrays.toString(b1));  
    38.         String s1 = new String(b1, "ISO8859-1");  
    39.         System.out.println("s1=" + s1);  
    40.   
    41.         System.out.println("----对s1进行ISO8859-1编码-----");  
    42.         // 对s1进行ISO8859-1编码  
    43.         byte[] b2 = s1.getBytes("ISO8859-1");// 欧洲编码  
    44.         System.out.println(Arrays.toString(b2));  
    45.   
    46.         String s2 = new String(b2, "GBK");  
    47.         System.out.println("s2=" + s2);  
    48.     }  
    49.   
    50. }  
    51.   
    52. /*output: 
    53. [-60, -29, -70, -61] 
    54. s1=你好,s2=你好 
    55. [-60, -29, -70, -61] 
    56. s3=浣犲ソ 
    57. [-28, -67, -96, -27, -91, -67] 
    58. s4=?? 
    59. [63, 63] 
    60. 原数据:你好 
    61. [-60, -29, -70, -61] 
    62. s1=???? 
    63. ----对s1进行ISO8859-1编码----- 
    64. [-60, -29, -70, -61] 
    65. s2=你好 
    66. */  

    四、综合练习

    五个学生,每个学生有3门课程的成绩,从键盘输入以上数据(姓名,三门课成绩),
    输入格式:如:zahngsan,30,40,60计算出总成绩,并把学生的信息和计算出的总分数高低按顺序存放在磁盘文件stud.txt中

    步骤:
    1、描述学生对象
    2、定义一个可操作学生对象的工具类

    思路:
    1、通过获取键盘录入一行的数据,并将该行数据的信息取出,封装成学生对象
    2、因为学生对象很多,则需要存储,使用集合,因为要对学生总分排序
    所以可以使用TreeSet
    3、将集合中的信息写入到一个文件中

      1. import java.io.*;  
      2. import java.util.*;  
      3.   
      4. //定义学生类    
      5. class Student implements Comparable<Student> {  
      6.     // 定义私有属性  
      7.     private String name;  
      8.     private int ma, cn, en;  
      9.     private int sum;  
      10.   
      11.     // 构造Student函数,初始化  
      12.     Student(String name, int ma, int cn, int en) {  
      13.         this.name = name;  
      14.         this.ma = ma;  
      15.         this.cn = cn;  
      16.         this.en = en;  
      17.         sum = ma + cn + en;  
      18.     }  
      19.   
      20.     // 覆写compareTo方法,按学生总成绩排序  
      21.     public int compareTo(Student s) {  
      22.         int num = new Integer(this.sum).compareTo(new Integer(s.sum));  
      23.         if (num == 0)  
      24.             return this.name.compareTo(s.name);  
      25.         return num;  
      26.     }  
      27.   
      28.     // 获取学生信息  
      29.     public String getName() {  
      30.         return name;  
      31.     }  
      32.   
      33.     public int getSum() {  
      34.         return sum;  
      35.     }  
      36.   
      37.     // 覆写hasdCode()和equals()方法,排除相同的两个学生  
      38.     public int hashCode() {  
      39.         return name.hashCode() + sum * 39;  
      40.     }  
      41.   
      42.     public boolean equals(Object obj) {  
      43.         if (obj instanceof Student)  
      44.             throw new ClassCastException("类型不匹配");  
      45.         Student s = (Student) obj;  
      46.         return this.name.equals(s.name) && this.sum == s.sum;  
      47.     }  
      48.   
      49.     // 定义学生信息显示格式  
      50.     public String toString() {  
      51.         return "student[" + name + ", " + ma + ", " + cn + ", " + en + "]";  
      52.     }  
      53. }  
      54.   
      55. // 工具类,将键盘录入的输入存入集合,并将集合的元素写入文件中  
      56. class StudentInfoTool {  
      57.     // 无比较器的学生集合  
      58.     public static Set<Student> getStudents() {  
      59.         return getStudents(null);  
      60.     }  
      61.   
      62.     // 具备比较器的学生集合  
      63.     @SuppressWarnings("finally")  
      64.     public static Set<Student> getStudents(Comparator<Student> cmp) {  
      65.         BufferedReader bufr = null;  
      66.         Set<Student> stus = null;  
      67.         try {  
      68.             // 创建读取流对象缓冲区,键盘录入  
      69.             bufr = new BufferedReader(new InputStreamReader(System.in));  
      70.             String line = null;  
      71.             // 选择集合是否有比较器  
      72.             if (cmp == null)  
      73.                 stus = new TreeSet<Student>();  
      74.             else  
      75.                 stus = new TreeSet<Student>(cmp);  
      76.             // 循环读取键盘录入的数据  
      77.             while ((line = bufr.readLine()) != null) {  
      78.                 if ("over".equals(line))  
      79.                     break;  
      80.                 // 对读取的数据进行分割并存入集合  
      81.                 String[] info = line.split(",");  
      82.                 Student stu = new Student(info[0], Integer.parseInt(info[1]),  
      83.                         Integer.parseInt(info[2]), Integer.parseInt(info[3]));  
      84.                 stus.add(stu);  
      85.             }  
      86.         } catch (IOException e) {  
      87.             throw new RuntimeException("学生信息读取失败");  
      88.         }  
      89.         // 关闭流资源  
      90.         finally {  
      91.             try {  
      92.                 if (bufr != null)  
      93.                     bufr.close();  
      94.             } catch (IOException e) {  
      95.                 throw new RuntimeException("读取流关闭失败");  
      96.             }  
      97.             return stus;  
      98.         }  
      99.     }  
      100.   
      101.     // 将数据写入指定文件  
      102.     public static void write2File(Set<Student> stus, String fileName) {  
      103.         BufferedWriter bufw = null;  
      104.         try {  
      105.             // 创建写入流对象  
      106.             bufw = new BufferedWriter(new FileWriter(fileName));  
      107.             // 循环写入数据  
      108.             for (Student stu : stus) {  
      109.                 bufw.write(stu.toString() + " ");  
      110.                 bufw.write(stu.getSum() + "");  
      111.                 bufw.newLine();  
      112.                 bufw.flush();  
      113.             }  
      114.         } catch (IOException e) {  
      115.             throw new RuntimeException("读取流关闭失败");  
      116.         }  
      117.         // 关闭流资源  
      118.         finally {  
      119.             try {  
      120.                 if (bufw != null)  
      121.                     bufw.close();  
      122.             } catch (IOException e) {  
      123.                 throw new RuntimeException("写入流关闭失败");  
      124.             }  
      125.         }  
      126.     }  
      127. }  
      128.   
      129. class Demo {  
      130.     public static void main(String[] args) {  
      131.         // 反转比较器,将成绩从大到小排  
      132.         Comparator<Student> cmp = Collections.reverseOrder();  
      133.         // 将录入的学生信息存入集合  
      134.         Set<Student> stus = StudentInfoTool.getStudents(cmp);  
      135.         // 将信息写入指定文件中  
      136.         StudentInfoTool.write2File(stus, "sudentinfo.txt");  
      137.     }  

  • 相关阅读:
    PHP与MongoDB简介|安全|M+PHP应用实例(转)
    在CentOS中安装gcc配置c语言开发环境(转)
    linux svn客户端入门心得(转)
    php socket成功实例
    PHP date函数参数详解(转)
    php socket(fsockopen)的应用实例
    文件字符输出流FileWriter
    TCP(socket)实例
    文件字符输入流FileReader
    卡曼滤波python
  • 原文地址:https://www.cnblogs.com/johnwang/p/3238726.html
Copyright © 2011-2022 走看看