黑马程序员 Java基础<十>---> IO流<3>-其他流对象简述

来源:互联网 发布:噪声测量软件 编辑:程序博客网 时间:2024/05/17 21:56

-----------android培训java培训、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()方法,读取文件中的对象,并返回这个对象


示例:

import java.io.*;//创建Person类,实现序列化class Person implements Serializable{//定义自身的序列化方式public static final long serialVersionUID = 42L;//定义私有属性private String name;private int age;transient String id;static String country = "cn";//构造Person类Person(String name,int age,String id,String country){this.name = name;this.age = age;this.id = id;this.country = country;}//覆写toString方法public String toString(){return name+ ":" + age + ":" + id + ":" + country;}}//对象序列化测试class ObjectStreamDemo{public static void main(String[] args){//对象写入流writeObj();//对象读取流readObj();}//定义对象读取流public static void readObj(){ObjectInputStream ois = null;try{//创建对象读取流ois = new ObjectInputStream(new FileInputStream("obj.txt"));//通过读取文件数据,返回对象Person p = (Person)ois.readObject();System.out.println(p);}catch (Exception e){throw new RuntimeException("写入文件失败");}//最终关闭流对象finally{try{if(ois!=null)ois.close();}catch (IOException e){throw new RuntimeException("写入流关闭失败");}}}//定义对象写入流public static void writeObj(){ObjectOutputStream oos = null;try{//创建对象写入流oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));//写入对象数据oos.writeObject(new Person("lisi",25,"01","cn"));}catch (Exception e){throw new RuntimeException("写入文件失败");}//关闭流资源finally{try{if(oos!=null)oos.close();}catch (IOException e){throw new RuntimeException("写入流关闭失败");}}}}


第二节   管道流

一、概述:

1、管道流:PipedInputStream和PipedOutputStream

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

二、使用步骤:

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

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

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

示例:

import java.io.*;//创建Read类,实现run方法class Read implements Runnable{private PipedInputStream in;Read(PipedInputStream in){this.in = in;}//实现run方法public void run(){try{//读取写入的数据//System.out.println("开始写入数据,等待时间");//测试用Thread.sleep(3000);byte[] b = new byte[1024];int len = in.read(b);//System.out.println("读取完毕");//测试用String s = new String(b,0,len);System.out.println(s);in.close();}catch (Exception e){throw new RuntimeException("管道流读取失败");}}}//创建Write类class Write implements Runnable{private PipedOutputStream out;//Write构造函数Write(PipedOutputStream out){this.out = out;}//实现run方法public void run(){try{//写入数据//System.out.println("开始写入数据");//测试用out.write("管道流来喽~~~~".getBytes());out.close();}catch (IOException e){throw new RuntimeException("管道流写入失败");}}}class PipedStreamDemo{public static void main(String[] args) throws IOException{//创建管道流对象PipedInputStream in = new PipedInputStream();PipedOutputStream out = new PipedOutputStream();//将读取流(输入流)和写入流(输出流)关联起来in.connect(out);//创建读写对象,并创建线程对象Read r = new Read(in);Write w = new Write(out);new Thread(r).start();new Thread(w).start();}}

第三节   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.跳过指定字节数


示例:

import java.io.*;//注:这几个函数内部都需要try,为测试,在函数上抛异常class RanAccFileDemo{public static void main(String[] args) throws IOException{//readRaf();readRaf2();//writeRaf();}//写入数据public static void writeRaf()throws IOException{//创建对象,写入数据RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");raf.write("王五".getBytes());raf.writeInt(99);raf.write("李四".getBytes());raf.writeInt(97);raf.close();}//读取数据public static void readRaf()throws IOException{//创建对象,读取数据RandomAccessFile raf = new RandomAccessFile("ran.txt","r");byte[] b = new byte[4];raf.read(b);String name = new String(b);int age = raf.readInt();System.out.println("name="+ name);System.out.println("age=" + age);raf.close();}//读取数据public static void readRaf2()throws IOException{//创建对象,读取数据RandomAccessFile raf = new RandomAccessFile("ran.txt","r");//调整对象中的指针//raf.seek(8);//跳过指定字节数raf.skipBytes(8);byte[] b = new byte[4];raf.read(b);String name = new String(b);int age = raf.readInt();System.out.println("name="+ name);System.out.println("age=" + age);raf.close();}}

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

一、概述:

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


示例:

import java.io.*;class ArrayStreamDemo{public static void main(String[] args){//数据源ByteArrayInputStream bais = new ByteArrayInputStream("ABCDEFF".getBytes());//数据目的ByteArrayOutputStream baos = new ByteArrayOutputStream();int by = 0;//读取和写入数据while((by=bais.read())!=-1){baos.write(by);}System.out.println(baos.size());System.out.println(baos.toString());try{//方法,此处抛异常,所以上面需要抛出去baos.writeTo(new FileOutputStream("a.txt"));}catch (IOException e){throw new RuntimeException("写入文件失败");}}}


第六节   字符编码

一、概述:

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中两个字节打头的相同,可以找到对应的符号,但不再是”联通“了。


示例:

import java.util.*;class EncodeDemo{public static void main(String[] args) throws Exception{CodeDemo();//编译成功,解码失败后的解决方式CodeBack();}public static void CodeDemo()throws Exception{String s = "你好";byte[] b1 = s.getBytes();String s1 = new String(b1);System.out.println(Arrays.toString(b1));byte[] b2 = s.getBytes("GBK");//默认编码String s2 = new String(b2);System.out.println("s1=" + s1 + ",s2=" + s2);System.out.println(Arrays.toString(b2));byte[] b3 = s.getBytes("UTF-8");//国际编码String s3 = new String(b3);System.out.println("s3=" + s3);System.out.println(Arrays.toString(b3));byte[] b4 = s.getBytes("ISO8859-1");//欧洲编码String s4 = new String(b4);System.out.println("s4=" + s4);System.out.println(Arrays.toString(b4));}//编码与解码public static void CodeBack()throws Exception{String s = "你好";System.out.println("原数据:" + s);byte[] b1 = s.getBytes("GBK");//默认编码System.out.println(Arrays.toString(b1));String s1 = new String(b1,"ISO8859-1");System.out.println("s1=" + s1);System.out.println("----对s1进行ISO8859-1编码-----");//对s1进行ISO8859-1编码byte[] b2 = s1.getBytes("ISO8859-1");//欧洲编码System.out.println(Arrays.toString(b2));String s2 = new String(b2,"GBK");System.out.println("s2=" + s2);}}


第七节   练习


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

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

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

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

import java.io.*;import java.util.*;//定义学生类class Student implements Comparable<Student>{//定义私有属性private String name;private int ma,cn,en;private int sum;//构造Student函数,初始化Student(String name,int ma,int cn,int en){this.name = name;this.ma = ma;this.cn = cn;this.en = en;sum = ma+cn+en;}//覆写compareTo方法,按学生总成绩排序public int compareTo(Student s){int num = new Integer(this.sum).compareTo(new Integer(s.sum));if(num==0)return this.name.compareTo(s.name);return num;}//获取学生信息public String getName(){return name;}public int getSum(){return sum;}//覆写hasdCode()和equals()方法,排除相同的两个学生public int hashCode(){return name.hashCode() + sum*39;}public boolean equals(Object obj){if(obj instanceof Student)throw new ClassCastException("类型不匹配");Student s = (Student)obj;return this.name.equals(s.name) && this.sum==s.sum;}//定义学生信息显示格式public String toString(){return "student[" + name + ", " + ma + ", " + cn + ", " + en + "]";}}//工具类,将键盘录入的输入存入集合,并将集合的元素写入文件中class StudentInfoTool{//无比较器的学生集合public static Set<Student> getStudents(){return getStudents(null);}//具备比较器的学生集合public static Set<Student> getStudents(Comparator<Student> cmp){BufferedReader bufr = null;Set<Student> stus = null;try{//创建读取流对象缓冲区,键盘录入bufr = new BufferedReader(new InputStreamReader(System.in));String line = null;//选择集合是否有比较器if(cmp==null)stus = new TreeSet<Student>();elsestus = new TreeSet<Student>(cmp);//循环读取键盘录入的数据while((line=bufr.readLine())!=null){if("over".equals(line))break;//对读取的数据进行分割并存入集合String[] info = line.split(",");Student stu = new Student(info[0],Integer.parseInt(info[1]),Integer.parseInt(info[2]),Integer.parseInt(info[3]));stus.add(stu);}}catch (IOException e){throw new RuntimeException("学生信息读取失败");}//关闭流资源finally{try{if(bufr!=null)bufr.close();}catch (IOException e){throw new RuntimeException("读取流关闭失败");}return stus;}}//将数据写入指定文件public static void write2File(Set<Student> stus,String fileName){BufferedWriter bufw = null;try{//创建写入流对象bufw = new BufferedWriter(new FileWriter(fileName));//循环写入数据for(Student stu : stus){bufw.write(stu.toString() + "\t");bufw.write(stu.getSum() + "");bufw.newLine();bufw.flush();}}catch (IOException e){throw new RuntimeException("读取流关闭失败");}//关闭流资源finally{try{if(bufw!=null)bufw.close();}catch (IOException e){throw new RuntimeException("写入流关闭失败");}}}}class Demo{public static void main(String[] args) {//反转比较器,将成绩从大到小排Comparator<Student> cmp = Collections.reverseOrder();//将录入的学生信息存入集合Set<Student> stus = StudentInfoTool.getStudents(cmp);//将信息写入指定文件中StudentInfoTool.write2File(stus,"sudentinfo.txt");}}






原创粉丝点击