IO原理
I/O是Input/Output的缩写, I/O技术是非常实用的技术, 用于处理设备之间的数据传输。 如读/写文件,网络通讯等。
Java程序中,对于数据的输入/输出操作以“流(stream)” 的方式进行。
java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。
流的分类
- 按操作数据单位不同分为: 字节流(8 bit),字符流(16 bit) ;
- 按数据流的流向不同分为: 输入流,输出流;
- 按流的角色的不同分为: 节点流,处理流。
(抽象基类) | 字节流 | 字符流 |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
流的体系结构:
抽象基类 | 节点流(文件流) | 缓冲流(处理流的一种) |
---|---|---|
InputStream | FileInputStream | BufferedInputStream |
OutputStream | FileOutputStream | BufferedOutputStream |
Reader | FileReader | BufferedReader |
Writer | FileWriter | BufferedWriter |
节点流和处理流
节点流
直接从数据源或目的地读写数据
处理流
处理流:不直接连接到数据源或目的地,而是“连接” 在已存在的流(节点流或处理流)之上,通过对数据的处理为程序提供更为强大的读写功能。
FileReader
- 实例化File类对象,指明要操作的文件
- 提供具体的流
- 数据的读入
- 流的关闭
注意点:
- read()的理解:返回读入的一个字符。如果达到文件末尾。返回-1;
- 异常的处理:try-catch-finally
- 读入的文件一定要存在,否则会报FileNotFoundException
举例:
使用read方法
public static void main(String[] args){// File file = new File("hello.txt");//相较于当前工程
// System.out.println(file.getAbsolutePath());//D:\Java\java_demo\hello.txt//1.FileReader fr = null;try {File file1 = new File("day09\\hello.txt");//相较于当前ModuleSystem.out.println(file1.getAbsolutePath());//D:\Java\java_demo\day09\hello.txt// 注意在单元测试中。直接写成 File file = new File("hello.txt");//2. 相当于提供了一个管道fr = new FileReader(file1);//3.// 方式一
// int data = fr.read();
// while(data != -1){
// System.out.print((char)data);
// data = fr.read();
// }// 方式二int data;while((data = fr.read()) != -1){System.out.print((char)data);}} catch (IOException e) {e.printStackTrace();} finally {//4.try {if(fr != null)// 万一上面没有造fr对象,就不用closefr.close();} catch (IOException e) {e.printStackTrace();}}}
使用read的重载方法
注意读入操作的两种方法:
//3.读入的操作 read(char[] cbub) :返回每次读入cbuf数组中的字符的个数,如果达到文件末尾,返回-1
char[] cbuf = new char[5];
int len;
while((len = fr.read(cbuf)) != -1){// 方式一for(int i=0;i<len;i++){System.out.print(cbuf[i]);//helloworld123ld}// 方式二String str = new String(cbuf,0,len);System.out.print(str);
}
public static void main(String[] args){FileReader fr = null;try {// 1. File类的实例化File file1 = new File("day09\\hello.txt");//相较于当前Module//2. FileReader流的实例化fr = new FileReader(file1);//3.读入的操作// read(char[] cbub) :返回每次读入cbuf数组中的字符的个数,如果达到文件末尾,返回-1char[] cbuf = new char[5];int len;while((len = fr.read(cbuf)) != -1){// 方式一:错误的写法
// for(int i=0;i<cbuf.length;i++){
// System.out.print(cbuf[i]);//helloworld123ld
// }
// // 方式二:对应着方式一的错误写法
// String str = new String(cbuf);
// System.out.print(str);//helloworld123ld
// //正确的写法
// for(int i=0;i<len;i++){
// System.out.print(cbuf[i]);//helloworld123ld
// }
//String str = new String(cbuf,0,len);System.out.print(str);}} catch (IOException e) {e.printStackTrace();} finally {//4.try {if(fr != null)fr.close();} catch (IOException e) {e.printStackTrace();}}}
FileWriter
步骤:
- 提供File类的对象,指明写出到的文件
- 提供FileWriter的对象,用于数据的写出
- 写出的操作
- 流资源的关闭
注意:
输出操作,对应的File可以不存在的。并不会报异常;
File对应的硬盘中的文件如果不存在,输出过程中自动创建此文件;
File对应的硬盘中的文件如果存在,如果流使用的构造器是
- FileWriter(file,false)/FileWriter(file):对原有文件的覆盖
- FileWriter(file,true):在原有内容上追加
举例:
public static void main(String[] args){FileWriter fw = null;try {//1.File file = new File("day09//hellowriter.txt");//2.fw = new FileWriter(file,true);//默认false,覆盖操作,true,追加//3.fw.write("You have a dream,\n");fw.write("I have a dream too.");} catch (IOException e) {e.printStackTrace();} finally {//4.try {if(fw != null)fw.close();} catch (IOException e) {e.printStackTrace();}}}
实现文本文件的复制
使用FileReader和FileWriter实现文本文件的复制
public static void main(String[] args) {FileReader fr = null;FileWriter fw = null;try {//1.创建File类的对象,指明读入和写出的文件File srcFile = new File("day09\\hi.txt");// 必须存在File destFile = new File("day09\\hi1.txt");//2.创建输入和输出流的对象fr = new FileReader(srcFile);fw = new FileWriter(destFile);//3. 数据的读入和写出操作char[] cbuf = new char[5];int len;//记录每次读入到cbuf数组中的字符的个数while((len = fr.read(cbuf)) != -1){//每次写出len个字符fw.write(cbuf,0,len);}} catch (IOException e) {e.printStackTrace();} finally {//4.关闭输入输出流try {if(fr != null)fr.close();} catch (IOException e) {e.printStackTrace();}try {if(fw != null)fw.close();} catch (IOException e) {e.printStackTrace();}}}
结论:
- 对于文本文件(txt,java,c,cpp),使用字符流处理;
- 对于非文本文件(jpg,mp3.mp4,avi,doc,ppt),使用字节流处理
- 只要不再控制台进行输出,采用字节流复制txt文件也是可以的
FileInputStream和FileOutputStream
字符流不能处理图片文件
//字符流不能处理图片文件
File srcFile = new File("day09\\hehe.jpg");// 必须存在
File destFile = new File("day09\\hehe1.jpg");//
字节流不能读取文本文件
使用FileInputStream不能读取文本文件的测试:stream.txt中有中文
public static void main(String[] args) {//1.FileInputStream fis = null;try {File file = new File("day09\\stream.txt");//2.fis = new FileInputStream(file);//3.byte[] buffer = new byte[5];int len;while((len = fis.read(buffer)) != -1){System.out.print(new String(buffer, 0, len));}} catch (IOException e) {e.printStackTrace();} finally {//4.try {if(fis != null)fis.close();} catch (IOException e) {e.printStackTrace();}}
}
实现对图片的复制
利用FileInputStream和FileOutputStream
public static void main(String[] args) {FileInputStream fis = null;FileOutputStream fos = null;try {//1.File srcPic = new File("day09\\hehe.jpg");File destPic = new File("day09\\hehe2.jpg");//2.fis = new FileInputStream(srcPic);fos = new FileOutputStream(destPic);//3.读入和写出byte[] buffer = new byte[5];int len;while((len = fis.read(buffer)) != -1){fos.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();} finally {//4.try {if(fis != null)fis.close();} catch (IOException e) {e.printStackTrace();}try {if(fos != null)fos.close();} catch (IOException e) {e.printStackTrace();}}}
指定路径下的文件复制
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;/*** @ClassName: FileInputOutputTStreamTest1* @author: benjamin* @version: 1.0* @description: TODO* @createTime: 2019/05/21/17:47*/public class FileInputOutputTStreamTest1 {public static void main(String[] args) {long start = System.currentTimeMillis();String srcPath = "day09\\demo.avi";String destPath ="day09\\测试.avi";copyFile(srcPath,destPath);long end = System.currentTimeMillis();System.out.println("复制操作花费的时间为:"+(end-start));}public static void copyFile(String srcPath,String destPath) {FileInputStream fis = null;FileOutputStream fos = null;try {//1.File srcPic = new File(srcPath);File destPic = new File(destPath);//2.fis = new FileInputStream(srcPic);fos = new FileOutputStream(destPic);//3.读入和写出byte[] buffer = new byte[1024];int len;while ((len = fis.read(buffer)) != -1) {fos.write(buffer, 0, len);}} catch (IOException e) {e.printStackTrace();} finally {//4.try {if (fis != null)fis.close();} catch (IOException e) {e.printStackTrace();}try {if (fos != null)fos.close();} catch (IOException e) {e.printStackTrace();}}}
}
缓冲流
BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter;
作用:提供流的读取、写入的速度
提高读写速度的原因:内部提供了一个缓冲区。
步骤:
- 造文件;
- 造流
- 造节点流
- 造缓冲流
- 复制的细节:读取、写入
- 资源关闭:先关闭外层的流,再关闭内层的流。说明,关闭外层
举例:
BufferedInputStream&BufferedOutputStream
BufferedInputStream和BufferedOutputStream实现非文本文件的复制
public static void main(String[] args) {FileInputStream fis = null;FileOutputStream fos = null;BufferedInputStream bis = null;BufferedOutputStream bos = null;try {//1.造文件File srcFile = new File("day09//hehe.jpg");File destFile = new File("day09//haha.jpg");//2.造流//2.1造节点流fis = new FileInputStream(srcFile);fos = new FileOutputStream(destFile);//2.2造缓冲流bis = new BufferedInputStream(fis);bos = new BufferedOutputStream(fos);//3.复制的细节:读取、写入byte[] buffer = new byte[10];int len;while((len = bis.read(buffer)) != -1){bos.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();} finally {//4. 关闭资源// 要求:先关闭外层的流,再关闭内层的流try {if(bos != null)bos.close();} catch (IOException e) {e.printStackTrace();}try {if(bis != null)bis.close();} catch (IOException e) {e.printStackTrace();}try {if(fos != null)fos.close();} catch (IOException e) {e.printStackTrace();}try {if(fis != null)fis.close();} catch (IOException e) {e.printStackTrace();}}
}
利用缓冲流实现指定路径下的文件复制,显然比节点流快
import java.io.*;/*** @ClassName: BufferedInputOutputStreamTest1* @author: benjamin* @version: 1.0* @description: 利用缓冲流实现指定路径下的文件复制,显然比节点流快* @createTime: 2019/05/21/21:54*/public class BufferedInputOutputStreamTest1 {public static void main(String[] args) {long start = System.currentTimeMillis();String srcPath = "day09\\demo.avi";String destPath = "day09\\demo2.avi";copyFileWithBuffered(srcPath,destPath);long end = System.currentTimeMillis();System.out.println("复制操作花费的时间为:"+(end-start));//219}public static void copyFileWithBuffered(String srcPath,String destPath){FileInputStream fis = null;FileOutputStream fos = null;BufferedInputStream bis = null;BufferedOutputStream bos = null;try {//1.造文件File srcFile = new File(srcPath);File destFile = new File(destPath);//2.造流//2.1造节点流fis = new FileInputStream(srcFile);fos = new FileOutputStream(destFile);//2.2造缓冲流bis = new BufferedInputStream(fis);bos = new BufferedOutputStream(fos);//3.复制的细节:读取、写入byte[] buffer = new byte[1024];int len;while((len = bis.read(buffer)) != -1){bos.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();} finally {//4. 关闭资源// 要求:先关闭外层的流,再关闭内层的流try {if(bos != null)bos.close();} catch (IOException e) {e.printStackTrace();}try {if(bis != null)bis.close();} catch (IOException e) {e.printStackTrace();}try {if(fos != null)fos.close();} catch (IOException e) {e.printStackTrace();}try {if(fis != null)fis.close();} catch (IOException e) {e.printStackTrace();}}}}
BufferReader & BufferWriter
实现文本文件的复制
import java.io.*;
import java.time.Period;/*** @ClassName: BufferedInputOutputStreamTest2* @author: benjamin* @version: 1.0* @description: 利用缓冲流实现文本文件复制* @createTime: 2019/05/21/21:54*/public class BufferedInputOutputStreamTest2 {public static void main(String[] args) {long start = System.currentTimeMillis();String srcPath = "day09\\dbcp.txt";String destPath = "day09\\dbcp2.txt";copyFileWithBuffered(srcPath,destPath);long end = System.currentTimeMillis();System.out.println("复制操作花费的时间为:"+(end-start));}public static void copyFileWithBuffered(String srcPath,String destPath){BufferedReader br = null;BufferedWriter bw = null;try {//1+2. 创建文件,创建节点流,创建缓冲流br = new BufferedReader(new FileReader(new File(srcPath)));bw = new BufferedWriter(new FileWriter(new File(destPath)));//3.读写操作// 方式一: 使用char型数组
// char[] cbuf = new char[1024];
// int len;
// while((len = br.read(cbuf)) != -1){
// bw.write(cbuf,0,len);
// bw.flush();
// }// 方式二:使用StringString data;while((data = br.readLine()) != null){//方法一:bw.write(data + "\n");//方法二:bw.write(data);//data中不含换行符bw.newLine();// 复制的文件中加入换行符}} catch (IOException e) {e.printStackTrace();} finally {//4.关闭资源try {if(bw != null)bw.close();} catch (IOException e) {e.printStackTrace();}try {if(br != null)br.close();} catch (IOException e) {e.printStackTrace();}}}}
总结:读写文件时调用的方法;
节点流:
FileInputStream:read(byte[] buffer)
FileOutputStream: write(byte[] buffer,0,len)
FileReader :read(char[] cbuf)
FileWriter: write(char[] cbuf,0,len)
缓冲流:
BufferInputStream:read(byte[] buffer)
BufferOutputStream: write(byte[] buffer,0,len)
BufferdReader:read(char[] cbuf)/readLine()
BufferedWriter:write(char[] cbuf,0,len/flush())
转换流
转换流:属于字符流
- InputStreamReader:将一个字节的输入流转换为字符的输入流,将InputStream转换为Reader
- OutputStreamWriter:将一个字符的输出流转化为字节的输出流,将Writer转换为OutputStream
作用:提供了在字节流和字符流之间的转换
解码:字节、字节数组 ---> 字符数组、字符串
编码:字符数组、字符串 ---> 字节、字节数组
4步:
- 造文件
- 造流
- 读写
- 关闭资源
public static void test1() {InputStreamReader isr = null;try {FileInputStream fis = new FileInputStream("day09\\dbcp.txt");// 参数指明了字符集,具体使用哪个字符集,取决于文件保存时实用的字符集isr = new InputStreamReader(fis,"UTF-8");
// InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集char[] cbuf = new char[20];int len;while((len = isr.read(cbuf)) != -1){String str = new String(cbuf,0,len);System.out.println(str);}} catch (IOException e) {e.printStackTrace();} finally {try {if(isr != null)isr.close();} catch (IOException e) {e.printStackTrace();}}}
public static void test2(){FileInputStream fis = null;FileOutputStream fos = null;InputStreamReader isr = null;OutputStreamWriter osw = null;try {//1.造文件File file1 = new File("day09\\dbcp.txt");File file2 = new File("day09\\dbcp_gbk.txt");//2. 造流fis = new FileInputStream(file1);fos = new FileOutputStream(file2);isr = new InputStreamReader(fis,"utf-8");osw = new OutputStreamWriter(fos,"gbk");//3.读写char[] cbuf = new char[20];int len;while((len = isr.read(cbuf)) != -1){osw.write(cbuf,0,len);}} catch (IOException e) {e.printStackTrace();} finally {//4.关闭资源try {if(isr != null)isr.close();} catch (IOException e) {e.printStackTrace();}try {if(osw != null)osw.close();} catch (IOException e) {e.printStackTrace();}try {if(fis != null)fis.close();} catch (IOException e) {e.printStackTrace();}try {if(fos != null)fos.close();} catch (IOException e) {e.printStackTrace();}}}
标准输入、输出流
System.in: 标准的输入流,默认从键盘输入
System.out: 标准的输出流,默认从控制台输出
System.in的类型是InputStream
System.out的类型是PrintStream,其是OutputStream的子类FilterOutputStream 的子类
重定向:通过System类的setIn, setOut方法对默认设备进行改变。
- public static void setIn(InputStream in)
- public static void setOut(PrintStream out)
举例:
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,直至当输入“ e”或者“ exit”时,退出程序。
方法一:使用Scanner实现,调用next()返回一个字符串
方法二:使用System.in实现。System.in ---> 转换流 ---> BufferedReader 的readLine()
public static void test1(){InputStreamReader isr = null;BufferedReader br = null;try {//1.将输出字符串通过转换流转为字节流isr = new InputStreamReader(System.in);br = new BufferedReader(isr);//2.读写while(true){String data = br.readLine();if("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)){System.out.println("程序结束");break;}String upperCase = data.toUpperCase();System.out.println(upperCase);}} catch (IOException e) {e.printStackTrace();} finally {//3.资源关闭try {if(isr != null)isr.close();} catch (IOException e) {e.printStackTrace();}try {if(br != null)br.close();} catch (IOException e) {e.printStackTrace();}}
}
打印流
实现将基本数据类型的数据格式转化为字符串输出
打印流: PrintStream和PrintWriter
- 提供了一系列重载的print()和println()方法,用于多种数据类型的输出
- PrintStream和PrintWriter的输出不会抛出IOException异
- PrintStream和PrintWriter有自动flush功能
- PrintStream 打印的所有字符都使用平台的默认字符编码转换为字节。
在需要写入字符而不是写入字节的情况下,应该使用 PrintWriter 类。
- System.out返回的是PrintStream的实例
public static void test2(){PrintStream ps = null;try {FileOutputStream fos = new FileOutputStream(new File("day09\\text.txt"));
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)ps = new PrintStream(fos, true);if (ps != null) {// 把标准输出流(控制台输出)改成文件System.setOut(ps);}for (int i = 0; i <= 255; i++) { // 输出ASCII字符System.out.print((char) i);if (i % 50 == 0) { // 每50个数据一行System.out.println(); // 换行}}} catch (FileNotFoundException e) {e.printStackTrace();} finally {if (ps != null) {ps.close();}}}
数据流
为了方便地操作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即可。
举例:
将内存中的字符串、基本数据类型的变量写出到文件中;将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中,读取不同数据类型的顺序要与当初写入文件时保存的数据的顺序一致。
public static void test3(){/** * @Description: 将内存中的字符串、基本数据类型的变量写出到文件中;* 并将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中* @Param: []* @return: void * @Author: benjamin* @Date: 2019/5/22*///1.DataOutputStream dos = null;try {dos = new DataOutputStream(new FileOutputStream("day09\\data.dat"));//2.dos.writeUTF("小强");//写UTF字符串dos.flush();//刷新操作,将内存中的数据写入文件dos.writeInt(23);dos.flush();dos.writeBoolean(true);//写入布尔值dos.flush();} catch (IOException e) {e.printStackTrace();} finally {//3.关闭操作try {if(dos != null)dos.close();} catch (IOException e) {e.printStackTrace();}}System.out.println("开始读操作了");//读操作DataInputStream dis = null;try {dis = new DataInputStream(new FileInputStream("day09\\data.dat"));String name = dis.readUTF();int age = dis.readInt();boolean isMale = dis.readBoolean();System.out.println("name = " + name);System.out.println("age = " + age);System.out.println("isMale = " + isMale);} catch (IOException e) {e.printStackTrace();} finally {try {if(dis != null)dis.close();} catch (IOException e) {e.printStackTrace();}}
}
对象流
ObjectInputStream和OjbectOutputSteam用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
- 序列化: 用ObjectOutputStream类保存基本类型数据或对象的机制
- 反序列化: 用ObjectInputStream类读取基本类型数据或对象的机制
如果需要让某个对象支持序列化机制,则必须让对象所属的类及其属性是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一。否则,会抛出NotSerializableException异常
凡是实现Serializable接口的类都有一个表示序列化版本标识符的静态变量:
- private static final long serialVersionUID;
- serialVersionUID用来表明类的不同版本间的兼容性。 简言之,其目的是以序列化对象进行版本控制,有关各版本反序列化时是否兼容。
- 如果类没有显示定义这个静态常量,它的值是Java运行时环境根据类的内部细节自动生成的。 若类的实例变量做了修改, serialVersionUID 可能发生变化。 故建议,显式声明。
简单来说, Java的序列化机制是通过在运行时判断类的serialVersionUID来验证版本一致性的。在进行反序列化时, JVM会把传来的字节流中的serialVersionUID与本地相应实体类的serialVersionUID进行比较,如果相同就认为是一致的,可以进行反序列化,否则就会出现序列化版本不一致的异常。 (InvalidCastException)
- Serializable
- Externalizable
对象的序列化机制
允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。
//当其它程序获取了这种二进制流,就可以恢复成原来的Java对象
序列化与反序列化的过程
若某个类实现了 Serializable 接口,该类的对象就是可序列化的:
- 创建一个 ObjectOutputStream
- 调用 ObjectOutputStream 对象的 writeObject(对象) 方法输出可序列化对象
- 注意写出一次,操作flush()一次
反序列化
- 创建一个 ObjectInputStream
- 调用 readObject() 方法读取流中的对象
强调: 如果某个类的属性不是基本数据类型或 String 类型,而是另一个引用类型,那么这个引用类型必须是可序列化的,否则拥有该类型的Field 的类也不能序列化
举例:
普通对象
import java.io.*;/*** @ClassName: ObjectOutputStreamTest* @author: benjamin* @version: 1.0* @description: 序列化与反序列化* @createTime: 2019/05/23/09:04*/public class ObjectOutputStreamTest {public static void main(String[] args) {// testObjectOutputStream();testObjectInputStream();}//序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去,使用ObjectOutputStream实现public static void testObjectOutputStream(){ObjectOutputStream oos = null;try {//1.oos = new ObjectOutputStream(new FileOutputStream("day10\\object.dat"));//2.oos.writeObject(new String("我爱北京天安门"));oos.flush();//刷新操作} catch (IOException e) {e.printStackTrace();} finally {//3.try {if(oos != null)oos.close();} catch (IOException e) {e.printStackTrace();}}}// 反序列化:将磁盘文件中的对象还原为内存中的一个java对象,使用ObjectInputStreampublic static void testObjectInputStream(){ObjectInputStream ois = null;try {ois = new ObjectInputStream(new FileInputStream("day10\\object.dat"));Object obj = ois.readObject();String str = (String) obj;System.out.println(str);} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} finally {try {if(ois != null)ois.close();} catch (IOException e) {e.printStackTrace();}}}
}
自定义类
实现序列化与反序列化操作
自定义一个Person类
- 需要实现接口:Serializable
- 当前类提供一个全局常量:serialVersionUID
- 除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性也必须是可序列化的。(默认情况下,基本数据库类型是可序列化的)
补充:
ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
import java.io.Serializable;/*** @ClassName: Person* @author: benjamin* @version: 1.0* @description: Person类要满足如下的需求,方可序列化;* 1、需要实现接口:Serializable* 2、当前类提供一个全局常量:serialVersionUID* 3、除了当前Person类需要实现Serializable接口之外,* 还必须保证其内部所有属性也必须是可序列化的。(默认情况下,基本数据库类型是可序列化的)* @createTime: 2019/05/22/21:52*/public class Person implements Serializable {public static final long serialVersionUID = 23686382323L;private String name;public int age;public String getName() {return name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}public Person(String name, int age) {this.name = name;this.age = age;}public Person() {}public void show(){System.out.println("你好,我是一个人");}private String showNation(String nation){System.out.println("我的国籍是:" + nation);return nation;}
}
import java.io.*;/*** @ClassName: ObjectOutputStreamTest* @author: benjamin* @version: 1.0* @description: 序列化与反序列化* @createTime: 2019/05/23/09:04*/public class ObjectOutputStreamTest {public static void main(String[] args) {testObjectOutputStream();testObjectInputStream();}//序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去,使用ObjectOutputStream实现public static void testObjectOutputStream(){ObjectOutputStream oos = null;try {//1.oos = new ObjectOutputStream(new FileOutputStream("day10\\object.dat"));//2.Stringoos.writeObject(new String("我爱北京天安门"));oos.flush();//自定义类实现序列化Person p1 = new Person("Tom",12);oos.writeObject(p1);oos.flush();//刷新操作} catch (IOException e) {e.printStackTrace();} finally {//3.try {if(oos != null)oos.close();} catch (IOException e) {e.printStackTrace();}}}// 反序列化:将磁盘文件中的对象还原为内存中的一个java对象,使用ObjectInputStreampublic static void testObjectInputStream(){ObjectInputStream ois = null;try {ois = new ObjectInputStream(new FileInputStream("day10\\object.dat"));Object obj = ois.readObject();String str = (String) obj;System.out.println(str);// 自定义类反序列化Person p = (Person) ois.readObject();System.out.println(p);} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} finally {try {if(ois != null)ois.close();} catch (IOException e) {e.printStackTrace();}}}
}
随机存取文件流
创建 RandomAccessFile 类实例需要指定一个 mode 参数,该参数指
定 RandomAccessFile 的访问模式:
r: 以只读方式打开
rw:打开以便读取和写入
rwd:打开以便读取和写入;同步文件内容的更新
rws:打开以便读取和写入; 同步文件内容和元数据的更新
如果模式为只读r。则不会创建文件,而是会去读取一个已经存在的文件,如果读取的文件不存在则会出现异常。 如果模式为rw读写。如果文件不存在则会去创建文件,如果存在则不会创建
RandomAccessFile的使用:
- 直接继承于java.lang.Object类,实现了DataInput和DataOutput接口;
- 既可以作为一个输入流,又可以作为一个输出类;
- 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建;如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)
- 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果
举例:
例1
public static void main(String[] args) {RandomAccessFile raf1 = null;RandomAccessFile raf2 = null;try {raf1 = new RandomAccessFile(new File("day10\\hehe.jpg"),"r");raf2 = new RandomAccessFile(new File("day10\\hehe1.jpg"),"rw");byte[] buffer = new byte[1024];int len;while((len = raf1.read(buffer)) != -1){raf2.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();} finally {try {if(raf1 != null)raf1.close();} catch (IOException e) {e.printStackTrace();}try {if(raf2 != null)raf2.close();} catch (IOException e) {e.printStackTrace();}}
例2
源文件内容为helloworld,变成xyzloworld
public static void test1(){RandomAccessFile raf1 = null;try {raf1 = new RandomAccessFile("day10\\hello.txt","rw");raf1.write("xyz".getBytes());} catch (IOException e) {e.printStackTrace();} finally {try {if(raf1 != null)raf1.close();} catch (IOException e) {e.printStackTrace();}}}
从指定位置插入覆盖原位置上的数据
public static void test2(){RandomAccessFile raf1 = null;try {raf1 = new RandomAccessFile("day10\\hello.txt","rw");raf1.seek(3);//将指针调到角标为3的位置raf1.write("xyz".getBytes());} catch (IOException e) {e.printStackTrace();} finally {try {if(raf1 != null)raf1.close();} catch (IOException e) {e.printStackTrace();}}}
例3
RandomAccessFile实现数据的插入
helloworld ==》helxyzloworld
// RandomAccessFile实现数据的插入
public static void test3(){RandomAccessFile raf1 = null;try {raf1 = new RandomAccessFile("day10\\hello.txt","rw");raf1.seek(3);//将指针调到角标为3的位置// 保存指针3后面的所有数据到StringBuider中StringBuilder builder = new StringBuilder((int)new File("hello.txt").length());byte[] buffer = new byte[20];int len;while((len = raf1.read(buffer)) != -1){builder.append(new String(buffer,0,len));}// 调回指针,写入"xyz"raf1.seek(3);raf1.write("xyz".getBytes());// 将StringBuilder中的数据写入到文件中raf1.write(builder.toString().getBytes());} catch (IOException e) {e.printStackTrace();} finally {try {if(raf1 != null)raf1.close();} catch (IOException e) {e.printStackTrace();}}
}
NIO.2中Path、Paths、File类的使用
Path可以看成是File类的升级版本,实际引用的资源也可以不存在。
NIO.2在java.nio.file包下还提供了Files、 Paths工具类, Files包含了大量静态的工具方法来操作文件; Paths则包含了两个返回Path的静态工厂方法。
Paths 类提供的静态 get() 方法用来获取 Path 对象:
- static Path get(String first, String … more) : 用于将多个字符串串连成路径
- static Path get(URI uri): 返回指定uri对应的Path路径
import org.apache.commons.io.FileUtils;import java.io.File;
import java.io.IOException;/*** @ClassName: PathCommonsioTest* @author: benjamin* @version: 1.0* @description: TODO* @createTime: 2019/05/22/15:11*/public class PathCommonsioTest {public static void main(String[] args) throws IOException {File srcFile = new File("day10\\hehe.jpg");File destFile = new File("day10\\hehe2.jpg");FileUtils.copyFile(srcFile,destFile);}}