当前位置:网站首页>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
边栏推荐
- Unity 安装 Device Simulator
- Developing NES game (cc65) 03 and VRAM buffer with C language
- Redis implements distributed locks
- FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be depreca
- [Nuxt 3] (十二) 项目目录结构 3
- VS1003 debugging routine
- Leetcode:704 binary search
- Pits encountered in MSP430 development (to be continued)
- Multi Chain and multi currency wallet system development cross chain technology
- 力扣315计算右侧小于当前元素的个数
猜你喜欢

SuperMap iclient3d for webgl to realize floating thermal map

设计一个线程池

New Oriental's single quarter revenue was 524million US dollars, a year-on-year decrease of 56.8%, and 925 learning centers were reduced

开源社区三十年 | 2022 开放原子全球开源峰会开源社区三十年专题活动圆满召开

The usage and Simulation Implementation of vector in STL

Redis implements distributed locks

FlexPro软件:生产、研究和开发中的测量数据分析

Ten prohibitions for men and women in love

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

Application and download of dart 3D radiative transfer model
随机推荐
Interface control telerik UI for WPF - how to use radspreadsheet to record or comment
Solution to the binary tree problem of niuke.com
Leetcode94. Middle order traversal of binary trees
大模型哪家强?OpenBMB发布BMList给你答案!
与元素类型 “item” 相关联的 “name” 属性值不能包含'<” 字符解决办法
连通块&&食物链——(并查集小结)
公司在什么情况下可以开除员工
Linear classifier (ccf20200901)
图书馆自动预约脚本
[base] what is the optimization of optimization performance?
01 pyechars 特性、版本、安装介绍
1331. 数组序号转换 : 简单模拟题
输入字符串,内有数字和非字符数组,例如A123x456将其中连续的数字作为一个整数,依次存放到一个数组中,如123放到a[0],456放到a[1],并输出a这些数
Library automatic reservation script
Deployment之滚动更新策略。
新零售电商O2O模式解析
LeetCode94. 二叉树的中序遍历
Sliding Window
20220728 common methods of object class
MySQL总是安装不成功,这样处理就好啦
Now that you see this, why don't you give it a compliment before you go