当前位置:网站首页>IO流再回顾,深入理解序列化和反序列化
IO流再回顾,深入理解序列化和反序列化
2022-07-28 11:48:00 【Zinksl】
文章目录

个人介绍
大家好我是:一颗松
认真分享技术,记录学习点滴
如果分享对你有用请支持我哦
点赞: 留言:收藏:️
个人格言: 想法落实的最佳时机就是现在!
1 InputStream

代码示例:
public class FileInputStreamDemo {
public static void main(String[] args) throws Exception {
// 定义文件路径
String str = "E:\\Codes\\myProject\\fileInputStreamTest.txt";
// 创建FileInputStream对象
FileInputStream fileInputStream = new FileInputStream(str);
// 创建一个8个字节的缓冲空间
byte buffer [] = new byte[8];
int length = 0;
while ((length = fileInputStream.read(buffer)) != -1){
System.out.println(new String(buffer,0,length));
}
}
}
2 OutputStream
代码示例:
此种方式数据写入文件,是覆盖源文件;
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("完成写入");
}
}
如果想实现数据写入文件,追加而不是覆盖则可以采用以下构造器:
- public FileOutputStream( filesrc, boolean append)
参数append为true时则,追加数据,不覆盖,
3 文件拷贝(字节流)
拷贝代码示例
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";
// 创建输入流对象
FileInputStream fileInputStreamDemo = new FileInputStream(str);
// 创建输出流对象
FileOutputStream fileOutputStream = new FileOutputStream(str2);
// 创建缓冲
byte buffer [] = new byte[8];
int leng = 0;
// 用循环实现拷贝
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("拷贝完成");
}
}
4 FileReader、 FileWriter

FileWriter同样有两种模式,覆盖模式,和追加模式;
覆盖模式;使用以下构造器
- public FileWriter( fileName)
使用下面构造器append 设置为true是是追加模式;
- public FileWriter( fileName, boolean append)
注意事项:FileWriter使用之后必须关闭(close)或者刷新(flush),否则写不到文件中;
5 文件拷贝(字符流)
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";
// 创建字符输入流
FileReader fileReader = new FileReader(str);
char [] array = new char[10];
int leng=0;
// 创建字符输出流
try {
FileWriter fileWriter = new FileWriter(str2);
while ((leng = fileReader.read(array)) !=-1){
String s =new String(array,0,leng);
fileWriter.write(s);
// 刷新字符输出流
fileWriter.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
}
}
}
6 节点流和处理流
节点流是针对某个特定的数据源读写,如FileWriter、FileReader;处理流也叫包装流,连接已存在的流,为程序提供更强大的功能如BufferWriter、BufferReader;
7 ObjectOutputSteam和ObjectInputStream—序列化和反序列化
此处理流(包装流),提供了对基本类型或者对象类型的序列化和反序列化的方法;
ObjectOutputStream:提供了序列化的方法
ObjectInputStream:提供了反序列化的方法
序列化: 就是将数据与数据类型都保存起来,叫序列化;
反序列化:指将序列化的数据恢复到原来;
注意:如果想让某个对象支持序列化,则必须让其类是可序列化的,也就是必须让类实现两个接口:
Sarializable:标记接口,没有方法(推荐使用)
Externalizable:该接口有方法需要实现
序列化代码示例:
public class SerializableDemo {
public static void main(String[] args) throws IOException {
// 创建被序列化对象
Person xiaoM = new Person("小明",18);
// 创建文件路径
String str = "E:\\Codes\\myProject\\ObjectOut.dat";
// 创建处理流对象
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(str));
outputStream.writeObject(xiaoM);
outputStream.close();
System.out.println("序列化完成");
}
}
class Person implements Serializable {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Person{name = " + name + ", age = " + age + "}";
}
}
反序列化代码示例:
public class ReSerializableDmeo {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// 定义变量接收,反序列化数据
Person person = null;
// 创建文件路径
String str = "E:\\Codes\\myProject\\ObjectOut.dat";
// 创建ObjectInputStream对象
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(str));
person = (Person) objectInputStream.readObject();
objectInputStream.close();
System.out.println("反序列化完成!");
System.out.println("姓名:"+person.getName()+" 年龄:"+person.getAge());
}
}
序列化过程中需要注意的事项:
(1):读写顺序要一致
(2):要实现序列化的的对象,类必须实现Serializable接口
(3):序列化类中建议添加 SerialVersionUID,可以提高版本兼容性
(4):序列化时会默认将里面所有属性都序列化了,但是被static和transient修饰的属性不会被序列化;
(5):序列化时要求里面属性的类型也需要实现序列化接口
(6):序列化具有可继承性
8 转换流
InputStreamReader和OutputStreamWriter
代码示例:
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();
}
}
结语
大佬请留步
既然看到这了不如点个赞再走吧
本文目的在于分享技术以及在学习过程中个人记得需要注意的点,记录学习过程;
如果出现错误欢迎大家指正,如有意见或建议欢迎在评论区讨论
边栏推荐
- Tik tok "founder" Yang Luyu, farewell byte?
- STM32 loopback structure receives and processes serial port data
- 用C语言开发NES游戏(CC65)04、完整的背景
- If you don't roll the golden nine and silver ten, it's too late
- Ten prohibitions for men and women in love
- [apue] 文件中的空洞
- Is it difficult for cloud native machine learning to land? Lingqueyun helps enterprises quickly apply mlops
- Did kafaka lose the message
- 非标自动化设备企业如何借助ERP系统,做好产品质量管理?
- 【萌新解题】爬楼梯
猜你喜欢

一台电脑上 多个项目公用一个 公私钥对拉取gerrit服务器代码

Implementation method of mouse hover, click and double click in ue4/5

设计一个线程池

If you don't roll the golden nine and silver ten, it's too late

金山云冲刺港股拟双重主要上市:年营收90亿 为雷军力挺项目

Brief discussion on open source OS distribution

What SaaS architecture design does a software architect need to know?

Did kafaka lose the message

Anhui Jingzhun: Beidou satellite synchronous clock | Beidou synchronous clock | NTP network clock server

How to realize more multimedia functions through the ffmpeg library and NaPi mechanism integrated in openharmony system?
随机推荐
FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will be depreca
[cute new problem solving] climb stairs
Kafaka丢消息吗
用C语言开发NES游戏(CC65)06、精灵
Anhui Jingzhun: Beidou satellite synchronous clock | Beidou synchronous clock | NTP network clock server
Foam exploded three times, why did Luo Yonghao put all his eggs in one basket to do ar?
[nuxt 3] (XII) project directory structure 3
Fastjson parses multi-level JSON strings
Developing NES games with C language (cc65) 11. Metatiles
Tik tok "founder" Yang Luyu, farewell byte?
STM32F103 several special pins are used as ordinary io. Precautions and data loss of backup register 1,2
Deployment之滚动更新策略。
[dark horse morning post] LETV 400 employees have no 996 and no internal papers; Witness history! 1 euro =1 US dollar; Stop immediately when these two interfaces appear on wechat; The crackdown on cou
sqli-labs(less-8)
输入字符串,内有数字和非字符数组,例如A123x456将其中连续的数字作为一个整数,依次存放到一个数组中,如123放到a[0],456放到a[1],并输出a这些数
Distributed session solution
让arduino支持nuvotom新唐
Using Arduino to develop esp8266 to build a development environment
MarkDown简明语法手册
Developing NES game (cc65) 03 and VRAM buffer with C language
既然看到这了不如点个赞再走吧