File operation learning (3) Standard stream, printing stream and serialization stream of file reading and writing

Standard stream and print stream

Although the standard stream and the print stream are relatively rare in daily life, these two are closely related to the underlying source code, so in order to discuss I/O operations in depth, you need to learn these two streams.

Standard stream

1. When we exchange information with ide, we also need input stream operation, and we have never seen direct input directly with stream, but will use a class, what is this class? What is its underlying principle?
__For problem one: __ Normally, we use the scanner class and ide to implement information input. The bottom layer of the scanner implements a packaging box enhancement to the input stream.
The standard stream includes the standard output stream and the standard input stream. Xiaoyan combines these streams into one example.

Case number one

Do not use scanner to realize input from the keyboard.

public class StandardStream {
    public static void main(String[] args) throws IOException {
        //InputStream in = System.in;
//        int by;
//        while ((by=in.read())!=-1){
//            System.out.println((char)by);
//        }
        //InputStreamReader isr = new InputStreamReader(in);
        //BufferedReader br = new BufferedReader(isr);
        System.out.println("------------------------------------------------");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line;
        System.out.println("请出入字符串:");
        while ((line = br.readLine())!=null){
            System.out.println("你输入的字符串是: "+line);
            if(line.equals("null")){
                break;
            }
        }
        System.out.println("请输入一个整数:");
        int i = Integer.parseInt(br.readLine());
        System.out.println("您输入的整数是:"+i);
        br.close();

        System.out.println("--------------------标准输出流练习--------------------");
        PrintStream ps =System.out;
        ps.print("hello");
        ps.print("world");
        System.out.println("hello");
        System.out.println("world");
        System.out.println("----------------------------");
    }
}

Operation result:
Insert picture description here
Conclusion: The essence of the output statement is a standard output stream.

Print stream

1. What is the difference between print stream and character output stream?
__For problem one: __ There are different operation methods for printing files and character output files.
Character output stream write file
In the constructor, you can see that there is another parameter autoFlush.

while ((line=br.readLine())!=null) {
      bw.write(line);
      bw.newLine();
      bw.flush();
}

Print stream write file

while ((line = br.readLine())!=null){
            pw.println(line);
        }

The comparison of the above two codes shows that the print stream is autoflush, and the character stream must be flushed by itself.

Case two

public class PrintDemo {
    public static void main(String[] args) throws IOException {
        printStream();
        printWriter();
        copyFiles();
    }
    public static void  printWriter() throws IOException {
        System.out.println("-----------字符打印流---------------");
//        PrintWriter pw = new PrintWriter("reader&writer\\PrintWriter.txt");
//        pw.write("hello");
//        pw.write("\r\n");
//        pw.flush();
//        //pw.write("world");
//        pw.println("world");
//        pw.flush();
        PrintWriter pw = new PrintWriter(new FileWriter("reader&writer\\PrintWriter.txt"),true);
         pw.println("hello");
//       pw.write("hello");
//       pw.write("\r\n");
//       pw.flush();
         pw.println("world");
         pw.close();
    }
    public static void printStream() throws FileNotFoundException {
        System.out.println("----------字节流打印流------------");
        PrintStream ps = new PrintStream("reader&writer\\PrintStream.txt");
        ps.println(97);
        ps.println(98);
        ps.println(99);
        ps.close();
        System.out.println("--------------------------------");
    }
    public static void  copyFiles() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("reader&writer\\src\\charbuffer\\PrintDemo.java"));
        PrintWriter pw = new PrintWriter(new FileWriter("reader&writer\\copy.java"),true);
        String line;
        while ((line = br.readLine())!=null){
            pw.println(line);
            System.out.println(line);
        }
        br.close();
        pw.close();
    }
}

The results of the operation achieve the expected results. The effects of
Insert picture description here
the two methods are the same. As for the efficiency, Xiao Ape is currently not too clear.

Serialization stream

1. Why do I need a serialized stream?
2. What caused the "java.io.NotSerializeableException" in the serialization stream? If you want to inherit an interface, why does the interface not implement methods?
3. After serializing an object with the object serialization stream, if the file of the object's class is modified, will there be any problems in reading the data? If something goes wrong, how to solve it?
4. If a member variable in an object does not want to be serialized, how can it be implemented?

__For problem one: __As an object, there are many problems in network transmission. It is not very inconvenient for the object to be directly transmitted on the network or stored in the hard disk. As for why it is inconvenient, please refer to Why serialization is required, so the sequence is introduced化流.
__For the second question: __ Need to implement the Serializable interface, the Serializable interface is an identifying interface, so there is no need to implement other methods or the like.
__For problem three: __ There will be problems. The serialization stream needs to generate a serialized version number before serializing the object, which is convenient for achieving version matching during deserialization. When the object file is modified, it will be thrown abnormal. After this, we need to modify the default rules. The modification method is to add the following code to make the serialized version consistent.

private static final long serialVersionUID =xxxx;

__For question four: __If you don't want a member variable to be serialized, you need to increase the price and add the keyword transient;

Case number one

To serialize the read and write person class, you must implement the Serializable interface.

public class Person implements Serializable {

    private static final long serialVersionUID =400;

    private String name;
    private int  age;
   private transient String  phoneNum;

    public Person() {
    }

    public Person(String name, int age, String phoneNum) {
        this.name = name;
        this.age = age;
        this.phoneNum = phoneNum;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPhoneNum() {
        return phoneNum;
    }

    public void setPhoneNum(String phoneNum) {
        this.phoneNum = phoneNum;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", phoneNum='" + phoneNum + '\'' +
                '}';
    }
}

Test class

public class SerilizableStream {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        write();
        read();
    }

    public static void write() throws IOException {
        //序列化
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("reader&writer\\SerializableOutStream.txt"));
        Person p1 = new Person("唐建秀", 31, "13883073323");
        oos.writeObject(p1);
        oos.close();
    }

    public static void read() throws IOException, ClassNotFoundException {
        //反序列化
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("reader&writer\\SerializableOutStream.txt"));
        Object o = ois.readObject();
        Person p=(Person)o;
        System.out.println(p);
        ois.close();
    }
}

Test results The
Insert picture description here
test results are in line with expectations.

Guess you like

Origin blog.csdn.net/xueshanfeitian/article/details/108844965