目录
- 0、介绍
- 1、FileInputStream 文件字节输入流
- 2、FileOutputStream 文件字节输出流
- 3、 FileInputStream + FileOutputStream 文件拷贝
- 4、FileReader 文件字符输入流
- 5、FileWriter 文件字符输出流
- 6、FileReader + FileWriter 文件拷贝
- 7、BufferedReader 带有缓冲区的字符输入流
- 8、InputStreamReader 字节流转换成字符流
- 9、BufferedWrite 带有缓冲的字符输出流 `OutputStreamWriter` 字节流转换成字符流
- 10、DataOutputStream 数据输入流
- 11、DataInputStream 数据输出流
- 12、PrintStream 标准的字节输出流
- 13、File类
- 14、序列化
0、介绍
1、什么是IO
- I : Input O : Output 通过IO可以完成硬盘文件的读和写。
2、流的分类
- 输入流、输出流、字节流、字符流
3、重要的流
- 文件专属:
- FileInputStream
- FileOutputStream
- FileReader
- FileWriter
- 转换流:(将字节流转换成字符流)
- InputStreamRead
- OutputStreamWriter
- 缓冲流专属:
- BufferedReader
- BufferedWriter
- BufferedInputStream
- BufferedOutputStream
- 数据流专属:
- DataInputStream
- DataOutputStream
- 标准输出流
- PrintWriter
- PrintStream
- 对象专属流:
- ObjectInputStream
- ObjectOutputStream
1、FileInputStream 文件字节输入流
- 文件字节输入流,万能的,任何类型的文件都可以采用这个流来读。
- 字节的方式,完成输入的操作,完成读的操作(硬盘—> 内存)
测试.txt的内容为:
a1 A
public class FileInputStreamTest01 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
// 创建文件字节输入流对象
fis = new FileInputStream("C:\\Users\\black\\Desktop\\测试.txt");
/*while(true) {
int readData = fis.read();
if(readData == -1) {
break;
}
System.out.println(readData);
}*/
// 改造while循环
int readData = 0;
// fis.read() 这个方法的返回值是:读取到的“字节”本身。 ASCII值
while((readData = fis.read()) != -1){
System.out.println(readData);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 在finally语句块当中确保流一定关闭。
if (fis != null) { // 避免空指针异常!
// 关闭流的前提是:流不是空。流是null的时候没必要关闭。
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 输出: 读取的输出是ASCII值。如果读不到数据 返回 -1
97 (a 的 ASCII 为 97)
49 (1 的 ASCII 为 49)
32 (空格的ASCII值 32)
65 (A 的 ASCII 为 65)
- 改进:
public class FileInputStreamTest04 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("测试.txt"); //注意此处路径是放到了项目的根目录
System.out.println("总字节数量:" + fis.available());
// 准备一个byte数组
byte[] bytes = new byte[4];
// fis.read(bytes)= -1 时是没有字符可以读取了 != -1 代表还可以继续读
// 此时的 readCount 读取到的字节数量。(不是字节本身) 要解码的 byte 数 的长度
int readCount = 0;
while((readCount = fis.read(bytes)) != -1) {
// 把byte数组转换成字符串,读到多少个转换多少个。
System.out.print(new String(bytes, 0, readCount));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 输出
总字节数量:4
97 (a 的 ASCII 为 97)
49 (1 的 ASCII 为 49)
32 (空格的ASCII值 32)
65 (A 的 ASCII 为 65)
2、FileOutputStream 文件字节输出流
-
负责写 内存 —> 硬盘。
-
以追加的方式在文件末尾写入。不会清空原文件内容。(true就是追加方式)
-
文件不存在的时候会自动新建!
fos = new FileOutputStream("tempfile3", true);
public class FileOutputStreamTest01 {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
// 这种方式谨慎使用,这种方式会先将原文件清空,然后重新写入。
//fos = new FileOutputStream("tempfile3");
// 以追加的方式在文件末尾写入。不会清空原文件内容。
fos = new FileOutputStream("测试.txt", true);
// 开始写。
byte[] bytes = {97, 98, 99, 100}; ASCII值
// 将byte数组全部写出!
fos.write(bytes); // 写入abcd
// 将byte数组的一部分写出!
fos.write(bytes, 0, 2); // 再写入ab
// 字符串
String s = "乌拉!!!";
byte[] bs = s.getBytes();// 将字符串转换成byte数组。
// 写
fos.write(bs);
// 写完之后,最后一定要刷新
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 输出
a1 Aabcdab乌拉!!!
3、 FileInputStream + FileOutputStream 文件拷贝
- 拷贝的过程应该是一边读,一边写
- 使用以上的字节流拷贝文件的时候,文件 类型随意,万能的。什么样的文件都能拷贝
public class Copy01 {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
// 创建一个输入流对象
fis = new FileInputStream("D:\\Java项目\\wula.mp4");
// 创建一个输出流对象
fos = new FileOutputStream("D:\\wula.mp4");
// 最核心的:一边读,一边写
byte[] bytes = new byte[1024 * 1024]; // 1MB(一次最多拷贝1MB。)
int readCount = 0;
while((readCount = fis.read(bytes)) != -1) {
fos.write(bytes, 0, readCount);
}
// 刷新,输出流最后要刷新
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 分开try,不要一起try。
// 一起try的时候,其中一个出现异常,可能会影响到另一个流的关闭。
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
4、FileReader 文件字符输入流
- 只能读取普通文本。读取文本内容时,比较方便,快捷
public class FileReaderTest {
public static void main(String[] args) {
FileReader reader = null;
try {
// 创建文件字符输入流
reader = new FileReader("tempfile");
// 开始读
char[] chars = new char[4]; // 一次读取4个字符
int readCount = 0;
while((readCount = reader.read(chars)) != -1) {
System.out.print(new String(chars,0,readCount));
}
/* 遍历
//准备一个char数组
char[] chars = new char[4];
// 往char数组中读
reader.read(chars); // 按照字符的方式读取:第一次a,第二次1,第三次 ,第四次A
for(char c : chars) {
System.out.println(c);
}
*/
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 输出
a1 A
5、FileWriter 文件字符输出流
- 写。只能输出普通文本。
public class FileWriterTest {
public static void main(String[] args) {
FileWriter out = null;
try {
// 创建文件字符输出流对象
//out = new FileWriter("file");
out = new FileWriter("file", true);
// 开始写。
char[] chars = {'A','B','C','D','E'};
out.write(chars);
out.write(chars, 2, 3);
out.write("乌拉!");
// 写出一个换行符。
out.write("\n");
out.write("hello world!");
// 刷新
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- 输出
ABCDECDE乌拉!
hello world!
6、FileReader + FileWriter 文件拷贝
- 只能拷贝“ 普通文本”文件。
public class Copy02 {
public static void main(String[] args) {
FileReader in = null;
FileWriter out = null;
try {
// 读
in = new FileReader("D://wulawula.txt");
// 写
out = new FileWriter("AAA.java");
// 一边读一边写:
char[] chars = new char[1024 * 512]; // 1MB
int readCount = 0;
while((readCount = in.read(chars)) != -1){
out.write(chars, 0, readCount);
}
// 刷新
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
7、BufferedReader 带有缓冲区的字符输入流
- 使用这个流的时候不需要自定义char数组,或者说不需要自定义byte数组。自带缓冲
public class BufferedReaderTest01 {
public static void main(String[] args) throws Exception{
FileReader reader = new FileReader("Copy02.java");
// 当一个流的构造方法中需要一个流的时候,这个被传进来的流叫做:节点流。
// 外部负责包装的这个流,叫做:包装流,还有一个名字叫做:处理流。
// 像当前这个程序来说:FileReader就是一个节点流。BufferedReader就是包装流/处理流。
BufferedReader br = new BufferedReader(reader);
// br.readLine()方法读取一个文本行,但不带换行符。
String s = null;
while((s = br.readLine()) != null){
System.out.print(s);
}
// 关闭流
// 对于包装流来说,只需要关闭最外层流就行,里面的节点流会自动关闭。(可以看源代码。)
br.close();
}
}
- 输出
ABCDEFGHIJKLMNOPQRSTUVWXYZ
8、InputStreamReader 字节流转换成字符流
- 通过转换流转换(InputStreamReader将字节流转换成字符流。)
public class BufferedReaderTest02 {
public static void main(String[] args) throws Exception{
/*// 字节流
FileInputStream in = new FileInputStream("Copy02.java");
// 通过转换流转换(InputStreamReader将字节流转换成字符流。)
// in是节点流。reader是包装流。
InputStreamReader reader = new InputStreamReader(in);
// 这个构造方法只能传一个字符流。不能传字节流。
// reader是节点流。br是包装流。
BufferedReader br = new BufferedReader(reader);*/
// 合并
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("Copy02.java")));
String line = null;
while((line = br.readLine()) != null){
System.out.println(line);
}
// 关闭最外层
br.close();
}
}
- 输出
ABCDEFGHIJKLMNOPQRSTUVWXYZ
9、BufferedWrite 带有缓冲的字符输出流 OutputStreamWriter
字节流转换成字符流
public class BufferedWriterTest {
public static void main(String[] args) throws Exception{
// 带有缓冲区的字符输出流
//BufferedWriter out = new BufferedWriter(new FileWriter("copy"));
BufferedWriter out = new BufferedWriter(new Outpu tStreamWriter(new FileOutputStream("copy", true)));
// 开始写。
out.write("hello world!");
out.write("\n");
out.write("hello kitty!");
// 刷新
out.flush();
// 关闭最外层
out.close();
}
}
hello world!
hello kitty!
10、DataOutputStream 数据输入流
- 写入数据专属的流
- 这个流可以将数据连同数据的类型一并写入文件。
- 注意:这个文件不是普通文本文档。(这个文件使用记事本打不开)
public class DataOutputStreamTest {
public static void main(String[] args) throws Exception{
// 创建数据专属的字节输出流
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data"));
// 写数据
byte b = 100;
short s = 200;
int i = 300;
long l = 400L;
float f = 3.0F;
double d = 3.14;
boolean sex = false;
char c = 'a';
// 写
dos.writeByte(b); // 把数据以及数据的类型一并写入到文件当中。
dos.writeShort(s);
dos.writeInt(i);
dos.writeLong(l);
dos.writeFloat(f);
dos.writeDouble(d);
dos.writeBoolean(sex);
dos.writeChar(c);
// 刷新
dos.flush();
// 关闭最外层
dos.close();
}
}
11、DataInputStream 数据输出流
- DataOutputStream写的文件,
只能
使用DataInputStream去读。并且读的时候你需要提前知道写入的顺序
。 - 读的顺序需要和写的
顺序一致
。才可以正常取出数据
public class DataInputStreamTest01 {
public static void main(String[] args) throws Exception{
DataInputStream dis = new DataInputStream(new FileInputStream("data"));
// 开始读
byte b = dis.readByte();
short s = dis.readShort();
int i = dis.readInt();
long l = dis.readLong();
float f = dis.readFloat();
double d = dis.readDouble();
boolean sex = dis.readBoolean();
char c = dis.readChar();
System.out.println(b);
System.out.println(s);
System.out.println(i + 1000);
System.out.println(l);
System.out.println(f);
System.out.println(d);
System.out.println(sex);
System.out.println(c);
dis.close();
}
}
12、PrintStream 标准的字节输出流
-
默认输出到控制台
-
可以改变标准输出流的方向
public class PrintStreamTest {
public static void main(String[] args) throws Exception{
// 联合起来写
System.out.println("hello world!");
// 分开写
PrintStream ps = System.out;
ps.println("hello zhangsan");
ps.println("hello lisi");
ps.println("hello wangwu");
// 标准输出流不需要手动close()关闭。
// 可以可以改变标准输出流的输出方向
/*
// 这些是之前System类使用过的方法和属性。
System.gc();
System.currentTimeMillis();
PrintStream ps2 = System.out;
System.exit(0);
System.arraycopy(....);
*/
// 标准输出流不再指向控制台,指向“log”文件。
PrintStream printStream = new PrintStream(new FileOutputStream("log"));
// 修改输出方向,将输出方向修改到"log"文件。
System.setOut(printStream);
// 再输出
System.out.println("hello world");
System.out.println("hello kitty");
System.out.println("hello zhangsan");
}
}
- 输出到指定的log文件
hello world
hello kitty
hello zhangsan
可以指定日志文件
/*
日志工具
*/
public class Logger {
/*
记录日志的方法。
*/
public static void log(String msg) {
try {
// 指向一个日志文件
PrintStream out = new PrintStream(new FileOutputStream("log.txt", true));
// 改变输出方向
System.setOut(out);
// 日期当前时间
Date nowTime = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String strTime = sdf.format(nowTime);
System.out.println(strTime + ": " + msg);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
- 调用
public class LogTest {
public static void main(String[] args) {
//测试工具类是否好用
Logger.log("调用了System类的gc()方法,建议启动垃圾回收");
Logger.log("调用了UserService的doSome()方法");
Logger.log("用户尝试进行登录,验证失败");
Logger.log("我非常喜欢这个记录日志的工具哦!");
}
}
- log.txt
2019-10-13 20:41:39 879: 调用了System类的gc()方法,建议启动垃圾回收
2019-10-13 20:41:39 936: 调用了UserService的doSome()方法
2019-10-13 20:41:39 936: 用户尝试进行登录,验证失败
2019-10-13 20:41:39 937: 我非常喜欢这个记录日志的工具哦!
13、File类
-
File类和四大家族没有关系,所以File类不能完成文件的读和写。
-
File对象代表什么
文件和目录路径名的抽象表示形式。 C:\Drivers 这是一个File对象 C:\Drivers\Lan\Realtek\Readme.txt 也是File对象。 一个File对象有可能对应的是目录,也可能是文件。 File只是一个路径名的抽象表示形式。
01、方法讲解
方法 | 解释 |
---|---|
exists | 判断File对象是否存在 |
createNewFile | 以文件的形式创建 |
mkdir | 以目录的形式创建 |
mkdirs | 多重目录的形式创建 |
getParent | 获得File对象的父路径(String形式返回) |
getParentFile | 获得File对象的父路径(File形式返回) |
getAbsolutePath | 获取绝对路径 |
getName | 获取文件名 |
isDirectory | 判断是否是一个目录 |
isFile | 判断是否是一个文件 |
lastModified | 获取文件最后一次修改时间(从1970年到现在的总毫秒数 |
length | 获取文件大小(字节) |
方法讲解1
public class FileTest01 {
public static void main(String[] args) throws Exception {
// 创建一个File对象
File f1 = new File("D:\\file");
// 判断是否存在!
System.out.println(f1.exists());
// 如果D:\file不存在,则以文件的形式创建出来
/*if(!f1.exists()) {
// 以文件形式新建
f1.createNewFile();
}*/
// 如果D:\file不存在,则以目录的形式创建出来
/*if(!f1.exists()) {
// 以目录的形式新建。
f1.mkdir();
}*/
// 可以创建多重目录吗?
File f2 = new File("D:/a/b/c/d/e/f");
/*if(!f2.exists()) {
// 多重目录的形式新建。
f2.mkdirs();
}*/
File f3 = new File("D:\\course\\01-开课\\学习方法.txt");
// 获取文件的父路径
String parentPath = f3.getParent();
System.out.println(parentPath); //D:\course\01-开课
File parentFile = f3.getParentFile();
System.out.println("获取绝对路径:" + parentFile.getAbsolutePath());
File f4 = new File("copy");
System.out.println("绝对路径:" + f4.getAbsolutePath()); // C:\Users\Administrator\IdeaProjects\javase\copy
}
}
方法讲解2
public class FileTest02 {
public static void main(String[] args) {
File f1 = new File("D:\\AAA.txt");
// 获取文件名
System.out.println("文件名 :" + f1.getName());
// 判断是否是一个目录
System.out.println("是否是一个目录 :" + f1.isDirectory()); // false
// 判断是否是一个文件
System.out.println("是否是一个文件 :" + f1.isFile()); // true
// 获取文件最后一次修改时间
long haoMiao = f1.lastModified(); // 这个毫秒是从1970年到现在的总毫秒数。
System.out.println("组后一次修改时间 "+ haoMiao);
// 将总毫秒数转换成日期?????
Date time = new Date(haoMiao);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String strTime = sdf.format(time);
System.out.println("日期 :" + strTime);
// 获取文件大小
System.out.println("文件大小 :" + f1.length()); //26字节。
}
}
- 输出
文件名:AAA.txt
是否是一个目录 :false
是否是一个文件 :true
组后一次修改时间 1588250195805 // 这个毫秒是从1970年到现在的总毫秒数。
日期 :2020-04-30 20:36:35 805
文件大小 :26 //字节
方法讲解3( 获取当前目录下所有的子文件。)
public class FileTest03 {
public static void main(String[] args) {
// File[] listFiles()
// 获取当前目录下所有的子文件。
File f = new File("D:\Java项目\018_springCloud");
File[] files = f.listFiles();
// foreach
for(File file : files){
//System.out.println(file.getAbsolutePath());
System.out.println(file.getName());
}
}
}
02、拷贝目录
public class CopyAll {
public static void main(String[] args) {
// 拷贝源
File srcFile = new File("D:\\course\\02-JavaSE\\document");
// 拷贝目标
File destFile = new File("C:\\a\\b\\c");
// 调用方法拷贝
copyDir(srcFile, destFile);
}
/**
* 拷贝目录
* @param srcFile 拷贝源
* @param destFile 拷贝目标
*/
private static void copyDir(File srcFile, File destFile) {
if(srcFile.isFile()) {
// srcFile如果是一个文件的话,递归结束。
// 是文件的时候需要拷贝。
// ....一边读一边写。
FileInputStream in = null;
FileOutputStream out = null;
try {
// 读这个文件
// D:\course\02-JavaSE\document\JavaSE进阶讲义\JavaSE进阶-01-面向对象.pdf
in = new FileInputStream(srcFile);
// 写到这个文件中
// C:\course\02-JavaSE\document\JavaSE进阶讲义\JavaSE进阶-01-面向对象.pdf
String path = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\") + srcFile.getAbsolutePath().substring(3);
out = new FileOutputStream(path);
// 一边读一边写
byte[] bytes = new byte[1024 * 1024]; // 一次复制1MB
int readCount = 0;
while((readCount = in.read(bytes)) != -1){
out.write(bytes, 0, readCount);
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
// 获取源下面的子目录
File[] files = srcFile.listFiles();
for(File file : files){
// 获取所有文件的(包括目录和文件)绝对路径
//System.out.println(file.getAbsolutePath());
if(file.isDirectory()){
// 新建对应的目录
//System.out.println(file.getAbsolutePath());
//D:\course\02-JavaSE\document\JavaSE进阶讲义 源目录
//C:\course\02-JavaSE\document\JavaSE进阶讲义 目标目录
String srcDir = file.getAbsolutePath();
String destDir = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\") + srcDir.substring(3);
File newFile = new File(destDir);
if(!newFile.exists()){
newFile.mkdirs();
}
}
// 递归调用
copyDir(file, destFile);
}
}
}
14、序列化
-
参与序列化和反序列化的对象,必须实现Serializable接口。
-
Serializable接口只是一个标志接口。起到标志的作用
java虚拟机看到这个类实现了这个接口,可能会对这个类进行特殊待遇。
Serializable这个标志接口是给java虚拟机参考的,java虚拟机看到这个接口之后,会为该类自动生成
一个序列化版本号。public interface Serializable { }
-
如果隔一段时间之后修改Java文件并且重新编译.反序列化时。会报错。
-
一旦代码确定之后,不能进行后续的修改,因为只要修改,必然会重新编译,此时会生成全新的序列化版本号,这个时候java虚拟机会认为这是一个全新的类。
所以需要手动确定一个序列号
java.io.InvalidClassException: com.bjpowernode.java.bean.Student; local class incompatible: stream classdesc serialVersionUID = -684255398724514298(十年后), local class serialVersionUID = -3463447116624555755(十年前)
-
如果某个字段不想被序列化,可以加入 transient 关键字表示游离的
作用
-
java语言中是采用什么机制来区分类的?
- 第一:首先通过类名进行比对,如果类名不一样,肯定不是同一个类。
- 第二:如果类名一样,再怎么进行类的区别?靠序列化版本号进行区分。
结论
-
凡是一个类实现了Serializable接口,建议给该类提供一个固定不变的序列化版本号。
这样,以后这个类即使代码修改了,但是版本号不变,java虚拟机会认为是同一个类。
案例1:一次序列化一个对象
- 实体类
@Data
@AllArgsConstructor //有参
@NoArgsConstructor //无参
public class Student implements Serializable {
// Java虚拟机看到Serializable接口之后,会自动生成一个序列化版本号。
// 这里没有手动写出来,java虚拟机会默认提供这个序列化版本号。
// 建议将序列化版本号手动的写出来。不建议自动生成
private static final long serialVersionUID = 1L; // java虚拟机识别一个类的时候先通过类名,如果类名一致,再通过序列化版本号。
private int no;
private String name;
}
- 序列化
public class ObjectOutputStreamTest01 {
public static void main(String[] args) throws Exception{
// 创建java对象
Student s = new Student(1111, "zhangsan");
// 序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("students"));
// 序列化对象
oos.writeObject(s);
// 刷新
oos.flush();
// 关闭
oos.close();
}
}
- 反序列化
public class ObjectInputStreamTest01 {
public static void main(String[] args) throws Exception{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("students"));
// 开始反序列化,读
Object obj = ois.readObject();
// 反序列化回来是一个学生对象,所以会调用学生对象的toString方法。
System.out.println(obj);
ois.close();
}
}
案例2:一次序列化多个对象 (可以将对象放到集合当中,序列化集合)
- 实体类
@Data
@AllArgsConstructor //有参
@NoArgsConstructor //无参
public class User implements Serializable {
private int no;
// transient关键字表示游离的,不参与序列化。
private transient String name; // name不参与序列化操作!
}
- 序列化
public class ObjectOutputStreamTest02 {
public static void main(String[] args) throws Exception{
List<User> userList = new ArrayList<>();
userList.add(new User(1,"zhangsan"));
userList.add(new User(2, "lisi"));
userList.add(new User(3, "wangwu"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("users"));
// 序列化一个集合,这个集合对象中放了很多其他对象。
oos.writeObject(userList);
oos.flush();
oos.close();
}
}
- 反序列化
public class ObjectInputStreamTest02 {
public static void main(String[] args) throws Exception{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("users"));
//Object obj = ois.readObject();
//System.out.println(obj instanceof List); //true
List<User> userList = (List<User>)ois.readObject();
for(User user : userList){
System.out.println(user);
}
ois.close();
}
}