黑马程序员-基础IO流(其他流)

来源:互联网 发布:源码商城开发公司 编辑:程序博客网 时间:2024/06/14 13:17

------- android培训、java培训、期待与您交流! ---------

 对象序列化

ObjectOutputStram和ObjectInputStream

一、概述:

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

二、特有方法:

1、write(int val)   --->  写入一个字节(最低八位)

2、writeInt(int vale)  --->   吸入一个32为int值

三、使用步骤:

说明:serialVersion

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

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

1、写入流对象:

1)创建对象写入流,与文件关联,即传入目的

2)通过写入writeObject()方法,将对象作为参数传入,即可写入文件

2、读取流对象

1)创建对象读取流,与文件关联,即传入源

2)通过writeObject()方法,读取文件中的对象,并返回这个对象


示例:

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


管道流

一、概述:

1、管道流:PipedInputStream和PipedOutputStream

2、管道流涉及到多线程的问题

二、使用步骤:

1、要先创建一个读和写的两个类,实现Runnable接口,因为是两个不同的线程,覆盖run方法,注意,需要在内部抛异常

2、创建两个管道流,并用connect()方法将两个流连接

3、创建读写对象,并传入两个线程内,并start执行

示例:

[java] view plaincopyprint?
  1. import java.io.*;  
  2.   
  3. //创建Read类,实现run方法  
  4. class Read implements Runnable{  
  5.     private PipedInputStream in;      
  6.     Read(PipedInputStream in){  
  7.         this.in = in;  
  8.     }  
  9.     //实现run方法  
  10.     public void run(){  
  11.         try{  
  12.             //读取写入的数据  
  13.             //System.out.println("开始写入数据,等待时间");//测试用  
  14.             Thread.sleep(3000);  
  15.             byte[] b = new byte[1024];  
  16.             int len = in.read(b);  
  17.             //System.out.println("读取完毕");//测试用  
  18.             String s = new String(b,0,len);  
  19.             System.out.println(s);  
  20.             in.close();  
  21.         }catch (Exception e){  
  22.             throw new RuntimeException("管道流读取失败");  
  23.         }  
  24.     }  
  25. }  
  26. //创建Write类  
  27. class Write implements Runnable{  
  28.     private PipedOutputStream out;  
  29.     //Write构造函数  
  30.     Write(PipedOutputStream out){  
  31.         this.out = out;  
  32.     }  
  33.     //实现run方法  
  34.     public void run(){  
  35.         try{  
  36.             //写入数据  
  37.             //System.out.println("开始写入数据");//测试用  
  38.             out.write("管道流来喽~~~~".getBytes());  
  39.             out.close();  
  40.         }catch (IOException e){  
  41.             throw new RuntimeException("管道流写入失败");  
  42.         }  
  43.     }  
  44. }  
  45. class PipedStreamDemo{  
  46.     public static void main(String[] args) throws IOException  
  47.     {  
  48.         //创建管道流对象  
  49.         PipedInputStream in = new PipedInputStream();  
  50.         PipedOutputStream out = new PipedOutputStream();  
  51.         //将读取流(输入流)和写入流(输出流)关联起来  
  52.         in.connect(out);  
  53.         //创建读写对象,并创建线程对象  
  54.         Read r = new Read(in);  
  55.         Write w = new Write(out);  
  56.         new Thread(r).start();  
  57.         new Thread(w).start();  
  58.     }  
  59. }  

RandomAccessFile 类

一、概述:

1、RandomAccessFile称之为随机访问文件的类,自身具备读写方法。

2、该类不算是IO体系中的子类,而是直接继承Object,但是它是IO包成员,因为它具备读写功能,内部封装了一个数组,且通过指针对数组的元素进行操作,同时可通过seek改变指针的位置。

3、可以完成读写的原理:内部封装了字节输入流

4、构造函数:RandomAccessFile(File file,String mode),可已从它的构造函数中看出,该类只能操作文件(也有字符串),而且操作文件还有模式。

模式传入值:”r“:以只读方式打开;”rw“:打开以便读写

如果模式为只读,则不会创建文件,会去读一个已存在的文件,若文件不存在,则会出现异常,如果模式为rw,且该对象的构造函数要操作的文件不存在,会自动创建,如果存在,则不会覆盖,也可通过seek方法修改。

二、特有方法:

1、seek(int n):设置指针,可以将指针设置到前面或后面

2、skipBytes(int n):跳过指定字节数,不可往前跳

三、使用步骤:

1、创建RandomAccessFile对象

2、将数据写入到指定文件中

3、读取数据,读入到指定文件中

注意:尧都区后面的数据,需要调用数组指针,通过改变角标位置,取出相应的数据

a.调整对象的指针:seek()

b.跳过指定字节数


示例:

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

操作基本数据类型的流对象

一、概述:

1、操作基本数据类型的流对象:DataInputStream和DataOutputStream

2、这两个读写对象,可用于操作基本数据类型的流对象,包含读写各种基本数据类型的方法

二、特有方法:

                                  读                                                    写

int型                 writeInt(int n)                               int readInt()

boolean型      writeBoolean(boolean b)         boolean readBoolean()

double型        writeDouble(double d)              double readDouble()

操作数组和字符串

一、操作字节数组的对象:ByteArrayInputStream和ByteArrayOutputStream

1、这个对象并没有调用底层资源,所以不用关闭流资源

2、存入的是缓冲区,并未用到键盘和硬盘灯,所以不需要抛任何IO异常

3、对象中封装了数组

4、构造函数:

1)ByteArrayInputStream:在构造函数的时候,需要接受数据源,而且数据源是一个字节数据。

2)ByteArrayOutputStream:在构造函数的时候,不用定义数据目的,因为该对象中已经在内部封装了可变长度的字节数组,这就是数据的目的地

4、因为两个流对象都是操作的是数据,并没有使用系统资源,所以不用进行close关闭。

6、其实就是用流的思想操作数组

7、特有方法:writeTo(OutputStream out) 这个方法用到了字节输出流,有异常存在,需要抛IO异常


二、对应的字符数组和字符串:

字符数组流对象:CharArrayReader和CharArrayWriter

字符串流对象:   StringReader和StringWriter


示例:

[java] view plaincopyprint?
  1. import java.io.*;  
  2. class ArrayStreamDemo  
  3. {  
  4.     public static void main(String[] args)  
  5.     {  
  6.         //数据源  
  7.         ByteArrayInputStream bais = new ByteArrayInputStream("ABCDEFF".getBytes());  
  8.         //数据目的  
  9.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  10.         int by = 0;  
  11.         //读取和写入数据  
  12.         while((by=bais.read())!=-1)  
  13.         {  
  14.             baos.write(by);  
  15.         }  
  16.         System.out.println(baos.size());  
  17.   
  18.         System.out.println(baos.toString());  
  19.           
  20.         try  
  21.         {  
  22.             //方法,此处抛异常,所以上面需要抛出去  
  23.             baos.writeTo(new FileOutputStream("a.txt"));  
  24.         }  
  25.         catch (IOException e)  
  26.         {  
  27.             throw new RuntimeException("写入文件失败");  
  28.         }  
  29.           
  30.     }  
  31. }  


字符编码

一、概述:

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

二、编码和解码:

1、编码:字符串变成字节数组

      解码:字节数组变成字符串

2、转换:

1)默认字符集:

      String  --->  byte[]   :srt.getBytes()

      byte[]   --->  String  :new String(byte[])

2)指定字符集:

      String  --->  byte[]   :srt.getBytes(charsetName)

      byte[]   --->  String  :new String(byte[],charsetName)

三、对于编码和解码的字符集转换

1、如果编码失败,解码就没意义了。

2、如果编码成功,解码出来的是乱码,,则需对乱码通过再次编码(用解错码的编码表),然后再通过正确的编码表解码。针对于IOS8859-1是通用的。

3、如果用的是GBK编码,UTF-8解码,那么再通过2的方式,就不能成功了,因为UTF-8也支持中文,在UTF-8解的时候,会将对应的字节数改变,所以不会成功。


四、特别注意:

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


示例:

[java] view plaincopyprint?
  1. import java.util.*;  
  2.   
  3. class EncodeDemo  
  4. {  
  5.     public static void main(String[] args) throws Exception{  
  6.         CodeDemo();  
  7.         //编译成功,解码失败后的解决方式  
  8.         CodeBack();  
  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.     public static void CodeBack()throws Exception{  
  33.         String s = "你好";  
  34.         System.out.println("原数据:" + s);  
  35.         byte[] b1 = s.getBytes("GBK");//默认编码  
  36.         System.out.println(Arrays.toString(b1));  
  37.         String s1 = new String(b1,"ISO8859-1");  
  38.         System.out.println("s1=" + s1);  
  39.           
  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. }  



  练习


五个学生,每个学生有3门课程的成绩,从键盘输入以上数据(姓名,三门课成绩),

输入格式:如:zahngsan,30,40,60计算出总成绩,并把学生的信息和计算出的总分数高低按顺序存放在磁盘文件stud.txt中

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

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

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