当前位置:网站首页>Review the IO stream again, and have an in-depth understanding of serialization and deserialization

Review the IO stream again, and have an in-depth understanding of serialization and deserialization

2022-07-28 12:48:00 Zinksl


 Insert picture description here
Personal introduction


Hello, I'm : A pine
Seriously share technology , Record what you learn
If sharing is useful to you, please support me

give the thumbs-up : Leaving a message. : Collection :️
Personal motto : The best time to implement an idea is now !


1 InputStream

 Insert picture description here

Code example :

public class FileInputStreamDemo {
    public static void main(String[] args) throws Exception {
//         Define file path 
        String str = "E:\\Codes\\myProject\\fileInputStreamTest.txt";
//         establish FileInputStream object 
        FileInputStream fileInputStream = new FileInputStream(str);
//         Create a 8 Buffer space of bytes 
        byte buffer [] = new byte[8];
        int length = 0;
        while ((length = fileInputStream.read(buffer)) != -1){
            System.out.println(new String(buffer,0,length));
        }

    }
}

2 OutputStream

Code example :

In this way, data is written to the file , Is to overwrite the source file ;

public class FileOutputSteamDemo {
    public static void main(String[] args) throws IOException {
        String str = "E:\\Codes\\myProject\\fileInputStreamTest.txt";
        OutputStream outputStream = new FileOutputStream(str);
        byte [] buffer = "gym.IverryverryLoveyou".getBytes();
        try {
            outputStream.write(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            outputStream.close();
        }
        System.out.println(" Write complete ");
    }
}

If you want to write data to a file , The following constructors can be used to append instead of overwrite :

  • public FileOutputStream( filesrc, boolean append)

Parameters append by true Time principle , Additional data , No coverage ,

3 A copy of a document ( Byte stream )

Copy the code example

public class IOCopyDemo {
    public static void main(String[] args) throws IOException {
        String str = "E:\\Codes\\myProject\\copyTest.txt";
        String str2 = "E:\\Codes\\myProject\\coptTest2.txt";
//         Create an input stream object 
        FileInputStream fileInputStreamDemo = new FileInputStream(str);
//         Create an output stream object 
        FileOutputStream fileOutputStream = new FileOutputStream(str2);
//         Create buffer 
        byte buffer [] = new byte[8];
        int leng = 0;
//         Copy with loop 
        try {
            while ((leng = fileInputStreamDemo.read(buffer))!=-1){
                fileOutputStream.write(buffer,0,leng);

            }
        } finally {
            if (fileOutputStream != null || fileInputStreamDemo != null){
                fileInputStreamDemo.close();
                fileOutputStream.close();
            }
        }
        System.out.println(" copy complete ");
    }
}

4 FileReader、 FileWriter

 Insert picture description here

FileWriter There are also two modes , Overlay mode , And append mode ;
Overlay mode ; Use the following constructors

  • public FileWriter( fileName)

Use the following constructor append Set to true Is the append mode ;

  • public FileWriter( fileName, boolean append)

matters needing attention :FileWriter It must be closed after use (close) Or refresh (flush), Otherwise, it cannot be written into the file ;

5 A copy of a document ( Character stream )

public class CopyDemo2 {
    public static void main(String[] args) throws FileNotFoundException {
        String  str = "E:\\Codes\\myProject\\fileWriter.txt";
        String str2 = "E:\\Codes\\myProject\\fileCopy.txt";
//         Create character input stream 
        FileReader fileReader = new FileReader(str);
        char [] array = new char[10];
        int leng=0;
//         Create character output stream 

        try {
            FileWriter fileWriter = new FileWriter(str2);
            while ((leng = fileReader.read(array)) !=-1){
                String s =new String(array,0,leng);
                fileWriter.write(s);
//                 Refresh the character output stream 
                fileWriter.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
    }
}

6 Node flow and processing flow

Node flows are read and write to a specific data source , Such as FileWriter、FileReader; Processing flow is also called packing flow , Connect to an existing stream , Provide more powerful functions for the program, such as BufferWriter、BufferReader;

7 ObjectOutputSteam and ObjectInputStream— Serialization and deserialization

This processing flow ( Packaging flow ), It provides methods for serialization and deserialization of basic types or object types ;
ObjectOutputStream: Provides a way to serialize
ObjectInputStream: Provides a method of deserialization

serialize : Is to save both data and data types , It's called serialization ;
Deserialization : It refers to restoring the serialized data to the original ;

Be careful : If you want an object to support serialization , Then its class must be serializable , That is, the class must implement two interfaces :
Sarializable: Tag interface , There is no way ( Recommended )
Externalizable: The interface has methods that need to be implemented
Serialization code example :

public class SerializableDemo {
    public static void main(String[] args) throws IOException {
//         Create serialized object 
        Person xiaoM = new Person(" Xiao Ming ",18);
//         Create file path 
        String str = "E:\\Codes\\myProject\\ObjectOut.dat";
//         Create a processing flow object 
        ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(str));
        outputStream.writeObject(xiaoM);
        outputStream.close();
        System.out.println(" Serialization complete ");
    }
}
class Person implements Serializable {
    private String name;
    private int age;

    public Person() {
    }

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

    /**
     *  obtain 
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     *  Set up 
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *  obtain 
     * @return age
     */
    public int getAge() {
        return age;
    }

    /**
     *  Set up 
     * @param age
     */
    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "Person{name = " + name + ", age = " + age + "}";
    }
}

Deserialization code example :

public class ReSerializableDmeo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
//         Define variable reception , Deserialized data 
        Person person = null;
        //         Create file path 
        String str = "E:\\Codes\\myProject\\ObjectOut.dat";
//         establish ObjectInputStream object 
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(str));
        person = (Person) objectInputStream.readObject();
        objectInputStream.close();
        System.out.println(" Deserialization complete !");
        System.out.println(" full name :"+person.getName()+"   Age :"+person.getAge());
    }
}

Precautions during serialization :
(1): Read and write in the same order
(2): The object to be serialized , Class must implement Serializable Interface
(3): It is suggested to add SerialVersionUID, Can improve version compatibility
(4): When serializing, all attributes in it will be serialized by default , But be static and transient The decorated property will not be serialized ;
(5): When serializing, the type of the attribute inside also needs to implement the serialization interface
(6): Serialization is inheritable

8 Converted flow

InputStreamReader and OutputStreamWriter
Code example :

public class InputStreamReaderDemo {
    public static void main(String[] args) throws IOException {
        String str = "E:\\Codes\\myProject\\fileWriter.txt";
        InputStreamReader inputStreamReader = new InputStreamReader(new  FileInputStream(str),"gbk");
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String s = null;
        while ((s = bufferedReader.readLine()) != null){
            System.out.println(s);
            bufferedReader.lines();
        }
        inputStreamReader.close();
        bufferedReader.close();
    }
}

Conclusion

Boss, please stay  Insert picture description here Now that you see this, why don't you give it a compliment before you go

The purpose of this article is to share the technology and the points that should be paid attention to in the learning process , Record the learning process ;
If there are mistakes, you are welcome to correct , If you have any comments or suggestions, please discuss them in the comment area

原网站

版权声明
本文为[Zinksl]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/209/202207281147572013.html