黑马程序员-基础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()方法,读取文件中的对象,并返回这个对象
示例:
- 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();
- }
- }
一、概述:
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>();
- else
- stus = 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");
- }
- }
- 黑马程序员-基础IO流(其他流)
- 黑马程序员----IO流(其他)
- 黑马程序员---IO其他流
- 黑马程序员--IO其他流
- 黑马程序员java基础之io流中的其他流
- 黑马程序员——Java基础---io流(io中的其他对象)
- 53.黑马程序员-IO流-其他流
- 黑马程序员-IO流其他流对象
- 黑马程序员_IO3_其他的IO流
- 黑马程序员--IO流04--其他类
- 黑马程序员-day20-IO流(其他类)
- 黑马程序员15.其他对象&IO流
- 黑马程序员--IO流之其他
- 黑马程序员----Java中的其他IO流
- 黑马程序员——IO流(其他流)
- (黑马程序员)IO流中的其他类总结(二)
- (黑马程序员)学习笔记,其他IO流对象
- 黑马程序员---IO流1(其他对象、FileWriter、FileReader)
- 第十一堂课后作业
- 快速排序
- Android之Adapter用法总结
- asp.net利用Ajax和Jquery在前台向后台传参数并返回值
- jquery validate 表单验证
- 黑马程序员-基础IO流(其他流)
- java读取pdf文件
- USACO/game1 3.3.5 博弈
- 关于NULL
- 【谷歌面试题】有序输出两棵二叉查找树中的元素
- 你的手机最近有没有3G问题?
- java 入门 二(基本数据类型与引用数据类型的区别)
- 从"0"开始
- 漫话中文自动分词和语义识别 - 中文分词算法