1File类
- java.io.File类: 文件和文件目录路径的抽象表示形式,与平台无关
- File 能新建、删除、重命名文件和目录,但 File不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入/输出流。
- 想要在Java程序中表示一个真实存在的文件或目录,那么必须有一个File对象,但是Java程序中的一个File对象,可能没有一个真实存在的文件或目录。
- File对象可以作为参数传递给流的构造器
- 构造函数:
- public File(String pathname) 以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。
- 绝对路径: 是一个固定的路径,从盘符开始
- 相对路径: 是相对于某个位置开始
- public File(String parent,String child) 以parent为父路径, child为子路径创建File对象。
- public File(File parent,String child) 根据一个父File对象和子文件路径创建File对象
- public File(String pathname) 以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。
- 路径中的每级目录之间用一个路径分隔符隔开。
- windows和DOS系统默认使用“\”来表示 ○ UNIX和URL使用“/”来表示
- Java程序支持跨平台运行,因此路径分隔符要慎用。
- 为了解决这个隐患, File类提供了一个常量:public static final String separator。根据操作系统,动态的提供分隔符。
例子:
File file1 = new File("d:\\fu\\info.txt");
File file2 = new File("d:" + File.separator + "fu" + File.separator + "info.txt");
File file3 = new File("d:/fu");
- File类的获取功能
- public String getAbsolutePath(): 获取绝对路径
- public String getPath() : 获取路径
- public String getName() : 获取名称
- public String getParent(): 获取上层文件目录路径。 若无, 返回null
- public long length() :获取文件长度(即:字节数) 。 不能获取目录的长度。
- public long lastModified() :获取最后一次的修改时间, 毫秒值
- public String[] list() : 获取指定目录下的所有文件或者文件目录的名称数组
- public File[] listFiles() : 获取指定目录下的所有文件或者文件目录的File数组
- File类的重命名功能
- public boolean renameTo(File dest):把文件重命名为指定的文件路径
- File类的判断功能
- public boolean isDirectory(): 判断是否是文件目录
- public boolean isFile() : 判断是否是文件
- public boolean exists() : 判断是否存在
- public boolean canRead() : 判断是否可读
- public boolean canWrite() : 判断是否可写
- public boolean isHidden() : 判断是否隐藏
- File类的创建功能
- public boolean createNewFile() : 创建文件。 若文件存在, 则不创建, 返回false
- public boolean mkdir() : 创建文件目录。 如果此文件目录存在, 就不创建。如果此文件目录的上层目录不存在, 也不创建。
- public boolean mkdirs() : 创建文件目录。 如果上层文件目录不存在, 一并创建
- 注意事项:如果你创建文件或者文件目录没有写盘符路径, 那么, 默认在项目路径下。
- File类的删除功能
- public boolean delete(): 删除文件或者文件夹
- 删除注意事项:Java中的删除不走回收站。要删除一个文件目录, 请注意该文件目录内不能包含文件或者文件目录
- public boolean delete(): 删除文件或者文件夹
案例
public class FileDemo1 {
/**
* File:表示文件或者目录
* @param args
*/
public static void main(String[] args) throws IOException {
//产生文件对象
File file = new File("d:\\file-test\\test1\\readme.txt");
System.out.println(File.separator);
File file2 = new File("d:\\file-test\\test1\\","readme.txt");
File file3 = new File("d:\\file-test\\test1\\","readme.txt");
File filePath = new File("d:\\file-test\\test1");
File file4 =new File(filePath,"readme.txt");
//产生目录
// file4.mkdir();//产生当前目录
if (!filePath.exists()){
filePath.mkdirs();// 创建文件目录。 如果上层文件目录不存在, 一并创建
}
file4.createNewFile();
//默认的文件目录
System.out.println(System.getProperties());
File file5 = new File("readme.txt");//user.dir,一般只在测试使用
file5.createNewFile();
// file5.delete();
System.out.println(file5.getAbsoluteFile());
System.out.println(file5.getPath());
System.out.println(file5.getName());
System.out.println(file5.length());
System.out.println("===================");
String[] files = filePath.list();
for (String s : files) {
System.out.println(s);
}
System.out.println(FileDemo1.class.getResource("/").getPath());//class path,一般文件放到
}
/**
* 递归目录,打印目录和子目录的文件
*
*/
public static void showFile(String path) {
File filePath = new File(path);
File[] files = filePath.listFiles();
for (File file : files) {
if (file.isDirectory()){
showFile(file.getAbsolutePath());
}else{
System.out.println(file.getPath());
}
}
}
@Test
public void test1(){
showFile("d:\\file-test");
}
}
2 IO流原理及流的分类
2.1 Java IO原理
- I/O是Input/Output的缩写, I/O技术是非常实用的技术, 用于处理设备之间的数据传输。 如读/写文件,网络通讯等。
- BIO,NIO,AIO
- Java程序中,对于数据的输入/输出操作以“流(stream)” 的方式进行。
- java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。
- 输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。
- 输出output: 将程序(内存)数据输出到磁盘、光盘等存储设备中。
2.2 IO流的分类
- 按操作数据单位不同分为: 字节流(8 bit),字符流
- 按数据流的流向不同分为: 输入流,输出流
(抽象基类) | 字节流 | 字符流 |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
分类 | 字节输入流 | 字节输出流 | 字符输入流 | 字符输出流 |
---|---|---|---|---|
抽象基类 | InputStream | OutputStream | Reader | Writer |
访问文件 | FileInputStream | FileOutputStream | FileReader | FileWriter |
访问数组 | ByteArrayInputStream | ByteArrayOutputStream | CharArrayReader | CharArrayWriter |
访问管道 | PipedInputStream | PipedOutputStream | PipedReader | PipedWriter |
访问字符串 | StringReader | StringWriter | ||
缓冲流 | BufferedInputStream | BuferedOutputStream | BufferedReader | BufferedWriter |
转换流 | InputStreamReader | OutputStreamWriter | ||
对象流 | ObjectOutputStream | ObjectOutputStream | ||
FilterInputStream | FilterOutputStream | FilterReader | FilterWriter | |
打印流 | PrintStream | PrintWriter | ||
推回打印流 | PushbackInputStream | PushbackReader | ||
特殊流 | DataInputStream | DataOutputStream |
- 节点流和处理流:
-
节点流:直接从数据源或目的地读写数据
-
处理流:不直接连接到数据源或目的地,而是“连接” 在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提供更为强大的读写功能。
-
3 字符流和字节流
3.1 InputStream & Reader
- InputStream 和 Reader 是所有输入流的基类。
- 程序中打开的文件 IO资源不属于内存里的资源,垃圾回收机制无法回收该资源,所以应该显式关闭文件 IO 资源。
- FileInputStream 从文件系统中的某个文件中获得输入字节。FileInputStream用于读取非文本数据之类的原始字节流。要读取字符流, 需要使用 FileReader
- InputStream
- int read() 从输入流中读取数据的下一个字节。 返回 0 到 255 范围内的 int 字节值。如果因为已经到达流末尾而没有可用的字节, 则返回值 -1。
- int read(byte[] b) 从此输入流中将最多b.length 个字节的数据读入一个 byte 数组中。 如果因为已经到达流末尾而没有可用的字节, 则返回值 -1。否则以整数形式返回实际读取的字节数。
- int read(byte[] b, int off,int len) 将输入流中最多len 个数据字节读入 byte 数组。 尝试读取 len 个字节, 但读取的字节也可能小于该值。 以整数形式返回实际读取的字节数。如果因为流位于文件末尾而没有可用的字节, 则返回值 -1。
- public void close() throws IOException 关闭此输入流并释放与该流关联的所有系统资源。
- Reader
- int read() 读取单个字符。作为整数读取的字符, 范围在 0 到 65535 之间 (0x00-0xffff)(2个字节的Unicode码) , 如果已到达流的末尾,则返回 -1
- int read(char[] cbuf) 将字符读入数组。 如果已到达流的末尾, 则返回 -1。否则返回本次读取的字符数。
- int read(char[] cbuf,int off,int len) 将字符读入数组的某一部分。存到数组cbuf中, 从off处开始存储, 最多读len个字符。 如果已到达流的末尾, 则返回 -1。 否则返回本次读取的字符数。
- public void close() throws IOException 关闭此输入流并释放与该流关联的所有系统资源。
3.2 OutputStream & Writer
- OutputStream
- void write(int b) 将指定的字节写入此输出流。 write的常规协定是:向输出流写入一个字节。 要写入的字节是参数 b 的八个低位。 b 的 24 个高位将被忽略。 即写入0~255范围的。
- void write(byte[] b) 将 b.length 个字节从指定的 byte 数组写入此输出流。 write(b)的常规协定是:应该与调用 write(b, 0, b.length) 的效果完全相同。
- void write(byte[] b,int off,int len) 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
- public void flush()throws IOException 刷新此输出流并强制写出所有缓冲的输出字节,调用此方法指示应将这些字节立即写入它们预期的目标。
- public void close() throws IOException关闭此输出流并释放与该流关联的所有系统资源。
- Writer
- void write(int c) 写入单个字符。要写入的字符包含在给定整数值的 16 个低位中, 16 高位被忽略。 即写入0 到 65535 之间的Unicode码。
- void write(char[] cbuf) 写入字符数组。
- void write(char[] cbuf,int off,int len) 写入字符数组的某一部分。 从off开始, 写入len个字符 ○ void write(String str) 写入字符串。
- void write(String str,int off,int len) 写入字符串的某一部分。
- **void flush()**刷新该流的缓冲, 则立即将它们写入预期目标。
- public void close() throws IOException关闭此输出流并释放与该流关联的所有系统资源。
- FileOutputStream 从文件系统中的某个文件中获得输出字节。FileOutputStream用于写出非文本数据之类的原始字节流。 要写出字符流, 需要使用 FileWriter
案例一
public class ReaderDemo1 {
/**
* 字符流:Reader -> FileReader
* 读取一个字符
*/
@Test
public void test1() {
FileReader reader = null;
try {
reader = new FileReader("readme.txt");
//读取一个字符
// char c = (char) reader.read();
// System.out.println(c);
int charInt = -1;//字符
//读取一个字符,如果返回 -1 表示到达文件末尾
while ((charInt = reader.read()) != -1) {
System.out.println((char) charInt);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 字符流:Reader -> FileReader
* 读取多个字符
*/
@Test
public void test2() {
FileReader reader = null;
try {
reader = new FileReader("readme.txt");
int length = -1;//读取的长度
char[] buffer = new char[5];//读取5个字符
// length = reader.read(buffer);
// System.out.println(buffer);
while ((length = reader.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, length));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
案例二
public class WriterDemo1 {
@Test
public void test1(){
FileWriter out = null;
try {
out = new FileWriter("a.txt");
out.write(97);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try{
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* 字符流,拷贝文件
*/
@Test
public void test2() {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("readme.txt");
out = new FileWriter("readme2.txt");
int length = -1;
char[] buffer = new char[5];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* 字符流,拷贝文件
*/
@Test
public void test3(){
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("a.jpg");
out = new FileWriter("a1.jpg");
int length = -1;
char[] buffer = new char[5];
while ((length = in.read(buffer)) != -1){
out.write(buffer,0,length);
}
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
案例三
public class InputStreamDemo1 {
/**
* 读取文件,如果有中文可能会有乱码
*
* @throws IOException
*/
@Test
public void test1() throws IOException {
FileInputStream in = new FileInputStream("readme.txt");
// int i = in.read();
// System.out.println((char) i);
// int i2 = in.read();
// System.out.println((char) i2);
int i = -1;
while ((i = in.read()) != -1) {
System.out.println((char) i);
}
in.close();
}
/**
* 拷贝,一个字节一个字节拷贝
*
* @throws IOException
*/
@Test
public void test2() throws IOException {
FileInputStream in = new FileInputStream("readme.txt");
FileOutputStream out = new FileOutputStream("readme2.txt");
int i = -1;
while ((i = in.read()) != -1) {
System.out.println((char) i);
out.write(i);
}
in.close();
out.close();
}
/**
* 拷贝,1k
*
* @throws Exception
*/
@Test
public void test3() throws IOException {
FileInputStream in = new FileInputStream("readme.txt");
FileOutputStream out = new FileOutputStream("readme3.txt");
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
/**
* 拷贝,1k
*
* @throws Exception
*/
@Test
public void test4() throws IOException {
FileInputStream in = new FileInputStream("a.jpg");
FileOutputStream out = new FileOutputStream("a1.jpg");
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}
块文件:字节流
文本文件:字符流和字节流,显示文件内容使用字符流
4 缓冲流
-
为了提高数据读写的速度, Java API提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8Kb)的缓冲区
-
缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:
- BufferedInputStream 和BufferedOutputStream
- BufferedReader 和 BufferedWriter
-
当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区
-
当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192个(8Kb),存在缓冲区中, 直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。
-
向流中写入字节时, 不会直接写到文件,先写到缓冲区中直到缓冲区写满,BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法flush()可以强制将缓冲区的内容全部写入输出流
-
关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可, 关闭最外层流也会相应关闭内层节点流
-
flush()方法的使用:手动将buffer中内容写入文件
-
如果是带缓冲区的流对象的close()方法, 不但会关闭流,还会在关闭流之前刷新缓冲区, 关闭后不能再写出
-
非缓冲流
-
缓冲流
案例
public class BufferCopy {
/**
* 使用非缓冲流拷贝
*
* @param from
* @param to
*/
public static void copyNoBuffer(String from, String to) {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(from);
out = new FileOutputStream(to);
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
// out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* 使用缓冲流拷贝
*
* @param from
* @param to
*/
public static void copyWithBuffer(String from, String to) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(from));
out = new BufferedOutputStream(new FileOutputStream(to));
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
// out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
out.close();//close会自动执行flush
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Test
public void test1() {
Long t1 = System.currentTimeMillis();
// copyNoBuffer("d:\\a.mkv", "d:\\a1.mkv");
copyWithBuffer("d:\\a.mkv", "d:\\a1.mkv");
Long t2 = System.currentTimeMillis();
System.out.println((t2 - t1) / 1000);
}
/**
* 字符缓冲流
*
* @throws Exception
*/
@Test
public void test2() throws Exception {
BufferedReader in = new BufferedReader(new FileReader("BufferCopy.txt"));
BufferedWriter out = new BufferedWriter(new FileWriter("BufferCopy2.txt"));
String line = null;
while ((line = in.readLine()) != null){
out.write(line);
out.newLine();
}
in.close();
out.close();
}
}
5 转换流
5.1 转换流
- 转换流提供了在字节流和字符流之间的转换
- 字节流中的数据都是字符时,转成字符流操作更高效。
- 很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能
- InputStreamReader
- 实现将字节的输入流按指定字符集转换为字符的输入流。
- 需要和InputStream“套接”。
- 构造器
- public InputStreamReader(InputStream in)
- public InputSreamReader(InputStream in,String charsetName) 如: Reader isr = new InputStreamReader(System.in,”gbk”);
- OutputStreamWriter
- 实现将字符的输出流按指定字符集转换为字节的输出流。
- 需要和OutputStream“套接”。
- 构造器
- public OutputStreamWriter(OutputStream out)
- public OutputSreamWriter(OutputStream out,String charsetName)
public class InputStreamReaderDemo {
@Test
public void test1() throws Exception {
InputStream in = new FileInputStream("utf8.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
System.out.println(reader.readLine());
}
}
5.2 字符编码(补充)
- 编码表的由来:计算机只能识别二进制数据,早期由来是电信号。为了方便应用计算机,让它可以识别各个国家的文字。就将各个国家的文字用数字来表示,并一一对应,形成一张表。这就是编码表。
- 常见的编码表
- ASCII: 美国标准信息交换码。
- 用一个字节的7位可以表示。
- ISO8859-1: 拉丁码表。欧洲码表
- 用一个字节的8位表示。
- GB2312: 中国的中文编码表。最多两个字节编码所有字符
- GBK: 中国的中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
- Unicode: 国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。
- UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
- ASCII: 美国标准信息交换码。
- Unicode不完美,这里就有三个问题,一个是,我们已经知道,英文字母只用一个字节表示就够了,第二个问题是如何才能区别Unicode和ASCII?计算机怎么知道两个字节表示一个符号,而不是分别表示两个符号呢?第三个,如果和GBK等双字节编码方式一样,用最高位是1或0表示两个字节和一个字节,就少了很多值无法用于表示字符,不够表示所有字符。Unicode在很长一段时间内无法推广,直到互联网的出现。
- 面向传输的众多 UTF(UCS Transfer Format)标准出现了,顾名思义, UTF-8就是每次8个位传输数据,而UTF-16就是每次16个位。这是为传输而设计的编码,并使编码无国界,这样就可以显示全世界上所有文化的字符了。
- Unicode只是定义了一个庞大的、全球通用的字符集,并为每个字符规定了唯一确定的编号,具体存储成什么样的字节流,取决于字符编码方案。推荐的Unicode编码是UTF-8和UTF-16。
public class InputStreamReaderDemo {
@Test
public void test1() throws Exception {
InputStream in = new FileInputStream("utf8.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
System.out.println(reader.readLine());
}
}
6 基于数组操作的流
ByteArrayInputStream:可以基于字节数组创建输入流
@Test
public void test1() throws Exception{
byte[] arr = {97,98,99,100,101,102};
ByteArrayInputStream in = new ByteArrayInputStream(arr);
int length = -1;
byte[] buffer = new byte[3];
while ((length = in.read(buffer)) != -1){
System.out.println(Arrays.toString(buffer));
}
}
ByteArrayOutputStream:可以把数据输出字节数组中
@Test
public void test2() throws Exception {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("hello.txt"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
int length = -1;
byte[] buffer = new byte[5];
while ((length = in.read(buffer)) != -1){
out.write(buffer,0,length);
}
byte[] data = out.toByteArray();// 得到输出流的字节
in.close();
out.close();
System.out.println(Arrays.toString(data));
}
CharArrayReader:基于字符数组产生输入流
@Test
public void test3() throws Exception {
char[] arr = {97,'b',99,100,101,102};
CharArrayReader in = new CharArrayReader(arr);
int length = -1;
char[] buffer = new char[3];
while ((length = in.read(buffer)) != -1){
System.out.println(Arrays.toString(buffer));
}
in.close();
}
CharArrayWriter:输出到字节数组中的输出流
@Test
public void test4() throws Exception {
BufferedReader in = new BufferedReader(new FileReader("hello.txt"));
CharArrayWriter out = new CharArrayWriter();
int length = -1;
char[] buffer = new char[5];
while ((length = in.read(buffer)) != -1) {
out.write(buffer,0,length);
}
char[] data = out.toCharArray();
in.close();
out.close();
System.out.println(Arrays.toString(data));
}
7 数据流
-
为了方便地操作Java语言的基本数据类型和String的数据,可以使用数据流。
-
数据流有两个类: (用于读取和写出基本数据类型、String类的数据)
- DataInputStream 和 DataOutputStream
- 分别“套接”在 InputStream 和 OutputStream 子类的流上
-
DataInputStream中的方法
- boolean readBoolean()
- byte readByte()
- char readChar()
- float readFloat()
- double readDouble()
- short readShort()
- long readLong()
- int readInt()
- String readUTF()
- void readFully(byte[] b)
-
DataOutputStream中的方法
- 将上述的方法的read改为相应的write即可
案例
@Test
public void test1() throws Exception {
DataOutputStream out = new DataOutputStream(new FileOutputStream("data.txt"));
out.writeChar('a');
out.writeChar(98);
out.writeInt(123);
out.writeUTF("ab中");
out.writeUTF("一二三四五六七");
out.close();
}
@Test
public void test2() throws Exception {
DataInputStream in = new DataInputStream(new FileInputStream("data.txt"));
// System.out.println(in.readLong());
System.out.println(in.readChar());
System.out.println(in.readChar());
System.out.println(in.readInt());
System.out.println(in.readUTF());
System.out.println(in.readUTF());
in.close();
}
结果如下
8 对象流
8.1 对象流简介
- ObjectInputStream和OjbectOutputSteam:用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
- 序列化: 用ObjectOutputStream类保存基本类型数据或对象的机制
- 反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
- ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
8.2 对象的序列化
-
对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。//当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
-
序列化的好处在于可将任何实现了Serializable接口的对象转化为字节数据,使其在保存和传输时可被还原
-
序列化是 RMI(Remote Method Invoke – 远程方法调用)过程的参数和返回值都必须实现的机制,而 RMI 是JavaEE 的基础。因此序列化机制是JavaEE 平台的基础
-
如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一。否则,会抛出NotSerializableException异常
- Serializable
- Externalizable
-
凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:
- private static final long serialVersionUID;
- serialVersionUID用来表明类的不同版本间的兼容性。简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。
- 如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。 若类的实例变量做了修改,serialVersionUID 可能发生变化。 故建议,显式声明。
-
简单来说,Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常。(InvalidCastException)
-
强调: 如果某个类的属性不是基本数据类型或 String类型,而是另一个引用类型,那么这个引用类型必须是可序列化的,否则拥有该类型的Field 的类也不能序列化
若idea中没有serialVersionUID警告,设置方法如下
案例一
User.java
public class User implements Serializable {
private static final long serialVersionUID = 7171965332457450126L;
static String CONFIG_NAME = "config name test";
private transient String address;
private int age;
private String name;
public User() {
}
public User(int age, String name, String address) {
this.age = age;
this.name = name;
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"address='" + address + '\'' +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
测试
/**
* 序列化:写对象
* 反序列化:读对象
* transient, static不会序列化(写)
* serialVersionUID:版本不一致报错InvalidClassException
*/
@Test
public void test1() throws Exception {
User user = new User(22,"张三","beijing");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("user"));
out.writeObject(user);
out.close();
System.out.println(user);
}
@Test
public void test2() throws Exception {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("user"));
User user = (User) in.readObject();
System.out.println(user);
}
结果如下
test1:
test2:
案例二
Bean.java
public class Bean implements Externalizable {
private static final long serialVersionUID = 1613877084589532427L;
char c1;
char c2;
int i;
public Bean() {
}
public Bean(char c1, char c2, int i) {
this.c1 = c1;
this.c2 = c2;
this.i = i;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeChar(c1);
out.writeChar(c2);
out.writeInt(i);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
i = in.readInt();
c1 = in.readChar();
c2 = in.readChar();
}
@Override
public String toString() {
return "Bean{" +
"c1=" + c1 +
", c2=" + c2 +
", i=" + i +
'}';
}
}
测试
@Test
public void test3() throws Exception {
Bean b = new Bean('a','b',2);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("bean"));
out.writeObject(b);
out.close();
System.out.println(b);
}
@Test
public void test4() throws Exception {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("bean"));
Bean b = (Bean) in.readObject();
System.out.println(b);
}
结果如下