当前位置:网站首页>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】
List of articles

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

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

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
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
边栏推荐
- 【一知半解】零值拷贝
- Did kafaka lose the message
- LeetCode206 反转链表
- LeetCode 移除元素&移动零
- 线性分类器(CCF20200901)
- HMS core audio editing service supports 7 kinds of audio effects to help one-stop audio processing
- New progress in the implementation of the industry | the openatom openharmony sub forum of the 2022 open atom global open source summit was successfully held
- 机器学习实战-神经网络-21
- C structure use
- The openatom openharmony sub forum was successfully held, and ecological and industrial development entered a new journey
猜你喜欢

Unity installs the device simulator

Ccf201912-2 recycling station site selection

VS1003 debugging routine

Aopmai biological has passed the registration: the half year revenue is 147million, and Guoshou Chengda and Dachen are shareholders

洪九果品通过聆讯:5个月经营利润9亿 阿里与中国农垦是股东

LeetCode84 柱状图中最大的矩形

DART 三维辐射传输模型申请及下载

MarkDown简明语法手册

Hongjiu fruit passed the hearing: five month operating profit of 900million Ali and China agricultural reclamation are shareholders

Interface control telerik UI for WPF - how to use radspreadsheet to record or comment
随机推荐
LeetCode 移除元素&移动零
IO流再回顾,深入理解序列化和反序列化
Unity loads GLB model
Multi Chain and multi currency wallet system development cross chain technology
Leetcode:704 binary search
Four authentic postures after suffering and trauma, Zizek
Uninstall Navicat: genuine MySQL official client, really fragrant!
STM32 loopback structure receives and processes serial port data
连通块&&食物链——(并查集小结)
Using dependent packages to directly implement paging and SQL statements
Leetcode94. Middle order traversal of binary trees
机器学习实战-神经网络-21
Merge sort
Application and download of dart 3D radiative transfer model
输入字符串,内有数字和非字符数组,例如A123x456将其中连续的数字作为一个整数,依次存放到一个数组中,如123放到a[0],456放到a[1],并输出a这些数
大模型哪家强?OpenBMB发布BMList给你答案!
Sliding Window
一台电脑上 多个项目公用一个 公私钥对拉取gerrit服务器代码
leetcode 1518. 换酒问题
Hc-05 Bluetooth module debugging slave mode and master mode experience
Now that you see this, why don't you give it a compliment before you go