zoukankan      html  css  js  c++  java
  • java笔记之IO详解——对象输入输出流、打印流、转换流

    对象的输入输出流 : 对象的输入输出流 主要的作用是用于写对象的信息与读取对象的信息。 对象信息一旦写到文件上那么对象的信息就可以做到持久化了

    对象的输出流: ObjectOutputStream .
    对象的输入流: ObjectInputStream

    对象输入输出流要注意的细节:
    1. 如果对象需要被写出到文件上,那么对象所属的类必须要实现Serializable接口。 Serializable接口没有任何的方法,是一个标识接口而已。
    2. 对象的反序列化创建对象的时候并不会调用到构造方法的、
    3. serialVersionUID 是用于记录class文件的版本信息的,serialVersionUID这个数字是通过一个类的类名、成员、包名、工程名算出的一个数字。

    Exception in thread "main" java.io.InvalidClassException: cn.file.iotest.User; local class incompatible: stream classdesc serialVersionUID = 5684219379304520675, local class serialVersionUID = 1432766954980686247
    at java.io.ObjectStreamClass.initNonProxy(Unknown Source)
    at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
    at java.io.ObjectInputStream.readClassDesc(Unknown Source)
    at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    at cn.file.iotest.Demo3.readObj(Demo3.java:75)
    at cn.file.iotest.Demo3.main(Demo3.java:62)

    4. 使用ObjectInputStream反序列化的时候,ObjeectInputStream会先读取文件中的serialVersionUID,然后与本地的class文件的serialVersionUID
    进行对比,如果这两个id不一致,那么反序列化就失败了。
    5. 如果序列化与反序列化的时候可能会修改类的成员,那么最好一开始就给这个类指定一个serialVersionUID,如果一类已经指定的serialVersionUID,然后
    在序列化与反序列化的时候,jvm都不会再自己算这个 class的serialVersionUID了。
    6. 如果一个对象某个数据不想被序列化到硬盘上,可以使用关键字transient修饰。
    7. 如果一个类维护了另外一个类的引用,那么另外一个类也需要实现Serializable接口。

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInput;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    
    class Address implements Serializable{
        
        String country;  
        String city;
        public Address(String country,String city){
            this.country = country;
            this.city = city;
        }
    }
    class User implements Serializable{
        
        private static final long serialVersionUID = 1L;//如果一类已经指定的serialVersionUID,然后
                                    //在序列化与反序列化的时候,jvm都不会再自己算这个 class的serialVersionUID了。 String userName ; String password; transient int age; // transient 透明 Address address ; public User(String userName , String passwrod) { this.userName = userName; this.password = passwrod; } public User(String userName , String passwrod,int age,Address address) { this.userName = userName; this.password = passwrod; this.age = age; this.address = address; } @Override public String toString() { return "用户名:"+this.userName+ " 密码:"+ this.password+" 年龄:"+this.age+" 地址:"+this.address.city; } } public class Demo3 { public static void main(String[] args) throws IOException, Exception { writeObj(); // readObj(); } //把文件中的对象信息读取出来-------->对象的反序列化 public static void readObj() throws IOException, ClassNotFoundException{ //找到目标文件 File file = new File("F:\obj.txt"); //建立数据的输入通道 FileInputStream fileInputStream = new FileInputStream(file); //建立对象的输入流对象 ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); //读取对象信息 User user = (User) objectInputStream.readObject(); //创建对象肯定要依赖对象所属 的class文件。 System.out.println("对象的信息:"+ user); } //定义方法把对象的信息写到硬盘上------>对象的序列化。 public static void writeObj() throws IOException{ //把user对象的信息持久化存储。 Address address = new Address("中国","广州"); User user = new User("admin","123",15,address); //找到目标文件 File file = new File("F:\obj.txt"); //建立数据输出流对象 FileOutputStream fileOutputStream = new FileOutputStream(file); //建立对象的输出流对象 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); //把对象写出 objectOutputStream.writeObject(user); //关闭资源 objectOutputStream.close(); } }

    打印流(printStream)  打印流可以打印任意类型的数据,而且打印数据之前都会先把数据转换成字符串再进行打印。

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintStream;
    class Animal{
        String color;
        String name;
        public Animal(String color,String name) {
                this.name=name;
                this.color=color;
        }
        @Override
        public String toString() {
            // TODO Auto-generated method stub
            return "颜色:"+this.color+" ,名称:"+this.name;
        }
    }
    public class TestPrint {
    
        public static void main(String[] args) throws FileNotFoundException {
            File file = new  File("F:\a.txt");
            //创建一个打印流
            PrintStream printStream = new PrintStream(file);
            printStream.println("sdff ");
            printStream.println(2.3213);
            printStream.println(false);
            printStream.println(2);
            printStream.println('g');    
            printStream.println(new Animal("黑色","穿靴子的猫"));
        }
    
    }

    收集异常的日志信息。

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    
    public class TestPrint {
    
        public static void main(String[] args) throws FileNotFoundException {
    
            File logFile = new File("F:\2015年1月8日.log");
            PrintStream logPrintStream = new PrintStream( new FileOutputStream(logFile,true) );
            try{
                int c = 4/0;
                System.out.println("c="+c);
                
            }catch(Exception e){
                e.printStackTrace(logPrintStream);
                
            }
            try {
                int[] arr = null;
                System.out.println(arr.length);
                
            } catch (Exception e) {
                e.printStackTrace(logPrintStream);
            }
        }
    
    }

    将异常写入a.txt文档中;

    java.lang.ArithmeticException: / by zero
    at cn.file.iotest.TestPrint.main(TestPrint.java:15)
    java.lang.ArithmeticException: / by zero
    at cn.file.iotest.TestPrint.main(TestPrint.java:15)
    java.lang.NullPointerException
    at cn.file.iotest.TestPrint.main(TestPrint.java:24)

    转换流:
    输入字节流的转换流:InputStreamReader 是字节流通向字符流的桥
    InputStreamReader
    输出字节流的转换流:
    OutputStreamWriter 可以把输出字节流转换成输出字符流 。
    转换流的作用:
    1. 如果目前所 获取到的是一个字节流需要转换字符流使用,这时候就可以使用转换流。 字节流----> 字符流
    2. 使用转换流可以指定编码表进行读写文件。

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    
    public class TestInputStreamRead {
    
        public static void main(String[] args) throws IOException {
            File file =new File("F:/test.txt");
            FileOutputStream fileOutputStream=new FileOutputStream(file);
            OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream,"utf-8");
            outputStreamWriter.write("中国");
            outputStreamWriter.close();
            read();
        }
        public static void read() throws IOException{
            File file =new File("D:\Eclipse\workspace\Test_001\my_test_Selenium\cn\file\iotest\Demo01.java");
            FileInputStream fileInputStream=new FileInputStream(file);
            InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream,"utf-8");
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            String  data=null;
    //        char[] buf = new char[1024];
            while ((data=bufferedReader.readLine())!=null) {
                System.out.println(data);
            }
            inputStreamReader.close();
        }
        
    
    }
  • 相关阅读:
    48. Rotate Image
    47. Permutations II
    46. Permutations
    45. Jump Game II
    44. Wildcard Matching
    43. Multiply Strings
    42. Trapping Rain Water
    41. First Missing Positive
    40. Combination Sum II
    39. Combination Sum
  • 原文地址:https://www.cnblogs.com/AllenRandolph/p/7018217.html
Copyright © 2011-2022 走看看