1. File类的使用
1.1 File类概述
- File类的一个对象,代表一个文件或一个文件目录(文件夹)
- File类声明在java.io包下
- File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成。
- File类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点"
1.2 创建File类的实例
- File类的构造器
- File(String filePath)
- File(String parentPath,String childPath)
- File(File parentFile,String childPath)
下面代码创建的都是内存层面的对象,还没有创建硬盘层面的具体文件
@Test
public void test1(){
//构造器1
File file1 = new File("hello.txt");//相对于当前module
File file2 = new File("D:\\workspace_idea1\\JavaSenior\\day08\\he.txt");
System.out.println(file1);
System.out.println(file2);
//构造器2:
File file3 = new File("D:\\workspace_idea1","JavaSenior");
System.out.println(file3);
//构造器3:
File file4 = new File(file3,"hi.txt");
System.out.println(file4);
}
- 相对路径与绝对路径
- 相对路径:相较于某个路径下,指明的路径。
- 写在main方法中是相对于当前工程
- 写在单元测试(Test)中是相对于当前模块
- 绝对路径:包含盘符在内的文件或文件目录的路径
- 路径分隔符
- Windows和DOS: \\
- unix和URL: /
1.3 File类中的常用方法
1.3.1 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数组
1.3.2 File类的重命名功能
- public boolean renameTo(File dest):把文件重命名为指定的文件路径
比如:file1.renameTo(file2)为例:
要想返回true,需要file1在硬盘中是存在的,且file2不能在硬盘中存在
File file1 = new File("hello.txt");
File file2 = new File("D:\\io\\hello.txt");
boolean renameTo = file2.renameTo(file1);
System.out.println(renameTo);
1.3.3 File类的判断功能
- public boolean isDirectory():判断是否是文件目录
- public boolean isFile() :判断是否是文件
- public boolean exists() :判断是否存在
- public boolean canRead() :判断是否可读
- public boolean canWrite() :判断是否可写
- public boolean isHidden() :判断是否隐藏
1.3.4 File类的创建功能
- public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
- public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
- public boolean mkdirs() :创建文件目录。如果上层文件目录不存在,一并创建。
注意:
- 如果你创建文件或者文件目录没有写盘符路径,默认在项目路径下。
- 这里的创建文件是真实的存储在硬盘上的文件
1.3.5 File的删除功能
public boolean delete():删除文件或者文件夹
删除注意事项:
- Java中的删除不走回收站。
- 要删除一个文件目录,请注意该文件目录内不能包含文件或者文件目录
2. 流的分类
按数据单位分类
- 字节流:一般用来处理图片视频 (Stream)
- 字符流:一般用来处理文本 (Reader/Writer)
按流的角色分类
- 节点流:可以从或向一个特定的地方(节点)读写数据。如FileReader.
- 处理流:是对一个已存在的流的连接和封装,通过所封装的流的功能调用实现数据读写。如BufferedReader.处理流的构造方法总是要带一个其他的流对象做参数。一个流对象经过其他流的多次包装,称为流的链接。
抽象基类
- InputStream
- OutputStream
- Reader
- Writer
节点流(或文件流) - FileInputStream (read(byte[] buffer))
- FileOutputStream (write(byte[] buffer,0,len)
- FileReader (read(char[] cbuf))
- FileWriter (write(char[] cbuf,0,len)
缓冲流(处理流的一种) - BufferedInputStream (read(byte[] buffer))
- BufferedOutputStream (write(byte[] buffer,0,len) / flush())
- BufferedReader (read(char[] cbuf) / readLine())
- BufferedWriter (write(char[] cbuf,0,len) / flush())
使用流的基本框架(重要!!!)
使用流的代码框架都是一致的
- 创建文件对象
- 创建流对象(节点流/处理流)
- 进行流的读写(输入输出)
- 关闭流(一般关闭最外层的处理流)
- 在编写的过程中注意异常的处理
3. 节点流
3.1 字符流(FileReader/FileWriter)
文本文件读入
Java中char类型的数据占2个字节
- int read()的理解:返回读入的一个字符。如果达到文件末尾,返回-1.
- 异常处理:为了保证流资源的关闭一定会执行。需要使用try-catch-finally处理,将close()放在finally中。
- 读入的文件一定要存在,否则就会报FileNotFoundException。
@Test
public void testFileReader() {
FileReader fr = null;
try{
//1. 实例化File对象,指明要操作的文件
File file = new File("hello.txt");
//2. 使用File对象创建字符流
fr = new FileReader(file);
//3. read()读入字符,到达文件末尾返回-1
int data;
while((data = fr.read())!=-1){
System.out.print((char)data);
}
} catch(IOException e) {
e.printStackTrace();
} finally {
//4. 关闭流
if(fr!= null){
try{
fr.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
上面的read()每次只能读一个字符,下面介绍一个read的重载方法可以一次读取一个字符数组char[]
int read(char[] cbuf);
返回每次读入chuf数组中的字符个数。如果到达文件末尾,返回-1。
//对read()操作升级:使用read的重载方法
@Test
public void testFileReader1() {
FileReader fr = null;
try {
//1.File类的实例化
File file = new File("hello.txt");
//2.FileReader流的实例化
fr = new FileReader(file);
//3.读入的操作
//read(char[] cbuf)
//返回每次读入cbuf数组中的字符个数。如果达到文件末尾,返回-1
char[] 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]);
// }
//正确写法
// for(int i = 0;i < len;i++){
// System.out.print(cbuf[i]);
// }
//方式二:
//错误的写法,对应着方式一的错误的写法
// String str = new String(cbuf);
// System.out.print(str);
//正确写法
String str = new String(cbuf, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
//4.资源的关闭
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文本文件写出
从内存中写出数据到硬盘的文件里。
- 输出操作需要写入的目标文件File可以不存在的,并不会报异常
- File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。File对应的硬盘中的文件如果存在:
- 如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
- 如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
//FileWriter构造器的定义如下
public FileWriter(File file, boolean append) throws IOException {
super(new FileOutputStream(file, append));
}
@Test
public void testFileWriter() {
FileWriter fw = null;
try {
//1.提供File类的对象,指明写出到的文件
File file = new File("hello1.txt");
//2.提供FileWriter的对象,用于数据的写出
fw = new FileWriter(file, false);
//3.写出的操作
fw.write("I have a dream!\n");
fw.write("you need to have a dream!");
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.流资源的关闭
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文本文件的复制(文件读入和写出的综合)
@Test
public void testFileReaderFileWriter() {
FileReader fr = null;
FileWriter fw = null;
try {
//1.创建File类的对象,指明读入和写出的文件
File srcFile = new File("hello.txt");
File destFile = new File("hello2.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 (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fr != null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.2 字节流(FileInputStream/FileOutputStream)
字节流用于处理非文本文件,不能处理文本文件(Java中char占两个字节)
- 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
- 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理
使用字节流FileInputStream和FileOutputStream复制图片
@Test
public void test(){
FileInputStream fis = null;
FileOutputStream fos = null;
try{
File srcfile = new File("图片.jpg");
File destfile = new File("新图片.jpg");
fis = new FileInputStream(srcfile);
fos = new FileOutputStream(destfile);
byte[] buffer = new byte[5];
int len;
while((len = fis.read(buffer))!=-1){
fos.write(buffer,0,len);
}
}catch (IOException e){
e.printStackTrace();
} finally{
if(fos!=null){
try{
fos.close();
} catch(IOException e){
e.printStackTrace();
}
}
if(fis!=null){
try{
fis.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
复制非文本文件的模板方法
public void copyFile(String srcPath,String destPath){
FileInputStream fis = null;
FileOutputStream fos = null
try{
File srcFile = new File(srcPath);
File destFile = new File(destPath);
fis = new FileInputStream(srcFile);
fos = new FileOutputStrewam(destFile);
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer))!=-1){
fos.write(buffer,0,len);
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(fis!=null){
try{
fis.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(fos!=null){
try{
fos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
4. 缓冲流(Buffered)(处理流之一)
处理流,就是“套接”在已有流的基础上。
作用:提高流的读取、写入的速度
原因:BufferedInputStream/BufferedInputStream内部提供了一个缓冲区(private static int DEFAULT_BUFFER_SIZE = 8192;)
4.1 缓冲流处理字节流(BufferedInputStream/BufferedOutputStream)
BufferedInputStream和BufferedOutputStream是处理流,需要在构造器中传入节点流(FileInputStream和FileOutputStream)
//实现非文本文件的复制
@Test
public void BufferedStreamTest() throws FileNotFoundException {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File("爱情与友情.jpg");
File destFile = new File("爱情与友情3.jpg");
//2.造流
//2.1 造节点流
FileInputStream fis = new FileInputStream((srcFile));
FileOutputStream 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);
// bos.flush();//刷新缓冲区
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
//要求:先关闭外层的流,再关闭内层的流
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
// fos.close();
// fis.close();
}
}
注意:
- 当Buffered流缓冲区满了后,读写方法中自动会调用flush方法,冲刷缓冲区,将内容写出。所以自己编程的时候不用显示的调用flush方法
4.2 缓冲流处理字符流(BufferedReader/BufferedWriter)
BufferedReader/BufferedWriter
文本文件的复制有两种方式:
- 一个个字符操作
- 使用br.readLine()方法一行一行地操作,到达文件末尾返回null
//使用BufferedReader和BufferedWriter实现文本文件的复制
@Test
public void testBufferedReaderBufferedWriter(){
BufferedReader br = null;
BufferedWriter bw = null;
try {
//创建文件和相应的流
br = new BufferedReader(new FileReader(new File("dbcp.txt")));
bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));
//读写操作
//方式一:使用char[]数组
// char[] cbuf = new char[1024];
// int len;
// while((len = br.read(cbuf)) != -1){
// bw.write(cbuf,0,len);
// }
//方式二:使用String
String data;
while((data = br.readLine()) != null){
//方法一:
// bw.write(data + "\n");//data中不包含换行符
//方法二:
bw.write(data);//data中不包含换行符
bw.newLine();//提供换行的操作
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if(bw != null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(br != null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.3 练习:统计文本中字符及其出现的次数
使用HashMap进行记录
/**
* 练习3:获取文本上字符出现的次数,把数据写入文件wordcount.txt
* 思路:
* 1.遍历文本每一个字符
* 2.字符出现的次数存在Map中
* Map<Character,Integer> map = new HashMap<Character,Integer>();
* 3.把map中的数据写入文件
*/
public class WordCount {
/*
说明:如果使用单元测试,文件相对路径为当前module
如果使用main()测试,文件相对路径为当前工程
*/
@Test
public void testWordCount() {
FileReader fr = null;
BufferedWriter bw = null;
try {
//1.创建Map集合
Map<Character, Integer> map = new HashMap<Character, Integer>();
//2.遍历每一个字符,每一个字符出现的次数放到map中
fr = new FileReader("dbcp.txt");
int c = 0;
while ((c = fr.read()) != -1) {
//int 还原 char
char ch = (char) c;
// 判断char是否在map中第一次出现
if (map.get(ch) == null) {
map.put(ch, 1);
} else {
map.put(ch, map.get(ch) + 1);
}
}
//3.把map中数据存在文件count.txt
//3.1 创建Writer
bw = new BufferedWriter(new FileWriter("wordcount.txt"));
//3.2 遍历map,再写入数据
Set<Map.Entry<Character, Integer>> entrySet = map.entrySet();
for (Map.Entry<Character, Integer> entry : entrySet) {
switch (entry.getKey()) {
case ' ':
bw.write("空格=" + entry.getValue());
break;
case '\t'://\t表示tab 键字符
bw.write("tab键=" + entry.getValue());
break;
case '\r'://
bw.write("回车=" + entry.getValue());
break;
case '\n'://
bw.write("换行=" + entry.getValue());
break;
default:
bw.write(entry.getKey() + "=" + entry.getValue());
break;
}
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.关流
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
5. 转换流(处理流之二)
转换流提供了在字节流和字符流之间的转换
Java API提供了2个转换流(转换流属于字符流):
- InputStreamReader:将InputStream转换为Reader
- OutputStreamWriter:将Writer转换为OutputStream
字节流中的数据都是字符时,转成字符流操作更高效。
很多时候使用转换流来处理文件乱码问题,实现编码和解码。
- 解码:字节、字节数组 —>字符数组、字符串
- 编码:字符数组、字符串 —> 字节、字节数组
站在程序的角度来看,就能理解转化流的作用
补充知识:字符集
- ASCII:美国标准信息交换码。用一个字节的7位可以表示。
- ISO8859-1:拉丁码表,欧洲码表。用一个字节的8位表示。
- GB2312:中文编码表。最多两个字节编码所有字符
- GBK:中文编码表升级,融合了更多的中文文字符号。最多两个字节编码
- Unicode:国际标准码,融合了目前人类使用的所有字符。为每个字符分配唯一的字符码。所有的文字都用两个字节来表示。
- UTF-8:变长的编码方式,可用1-4个字节来表示一个字符。
UTF编码集
Unicode有缺陷,为了解决Unicode的缺陷推出了UTF编码集。
UTF(UCS Transfer Format)。
顾名思义,UTF-8就是每次8个位传输数据,而UTF-16就是每次16个位。这是为传输而设计的编码,并使编码无国界,这样就可以显示全世界上所有文化的字符了。
Unicode只是定义了一个庞大的、全球通用的字符集,并为每个字符规定了唯一确定的编号,具体存储成什么样的字节流,取决于字符编码方案。推荐的
Unicode编码是UTF-8和UTF-16。
注:
- GBK等双字节编码方式中
- 最高位为0,一个字节表示一个字符
- 最高位为1,两个字节表示一个字符
- ANSI编码通常指平台的默认编码,例如英文操作系统中式ISO-8859-1,中文系统是GBK
Unicode的作用是为全世界每个字符指定一个固定的数字,而世界上的所有字符的个数大于2的15次方,小于2的16次方。
因为存在多个字节存储一个字符的情况,所以需要某些标记指明到底是几个字节组成当前的字符。
GBK中采取字节开头指定0/1的方式,Unicode使用如下的方式(以UTF-8为例)
如何查看一个文本文件的格式?
使用记事本(notepad)打开文本文件,看右下角的编码集就可以知道文件采用的编码集。
如果想要修改文件的编码集,可以将文件另存为选择想要的格式进行保存。
字节流(InputStream) -> 字符流(Reader)
//此时异常处理的话,仍然应该使用try-catch-finally
//InputStreamReader的使用,实现字节的输入流到字符的输入流的转换
@Test
public void test1() throws IOException {
FileInputStream fis = new FileInputStream("dbcp.txt");
// InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
//参数2指明了字符集,具体使用哪个字符集取决于文件dbcp.txt保存时使用的字符集
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf)) != -1){
String str = new String(cbuf,0,len);
System.out.print(str);
}
isr.close();
}
使用转换流将UTF-8格式的文本转化为GBK格式的文件
//完整的代码还需要使用try-catch-finally处理异常
@Test
public void test2() throw Exception{
//1. 造文件
File srcFile = new File("dbcp.txt");
File destFile = new File("dbcp_gbk.txt");
//2. 造流
FileInputStream fis = new FileInputStream(srcFile);
InputStreamReader isr = new InputStreamReader(fis."utf-8");
FileOutputStream fos = new FileOutputStream(destFile);
OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");
//3. 读写
char[] cbuff = new char[64];
int len;
while((len = isr.read())!=-1){
osw.write(cbuff,0,len);
}
//4. 关闭流(关闭最外层的流,内部的流也会自动关闭)
isr.close();
osw.close();
}
6. 标准输入、输出流(System.in,System.out)(处理流之三)
-
- System.in:标准的输入流,默认从键盘输入
- System.out:标准的输出流,默认从控制台输出
- System类的setIn(InputStream is) / setOut(PrintStream ps)可以重新指定输入、输出的位置。
-
- System.in是InputStream类型的变量
- System.out的类型是PrintStream,其是OutputStream的子类
FilterOutputStream 的子类
练习
从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,直至当输入“e”或者“exit”时,退出程序。
- 方法一:使用Scanner实现,调用next()返回一个字符串
- 方法二:使用System.in实现。System.in(字节流) —> 转换流 —> BufferedReader的readLine()
public static void main(String[] args) {
BufferedReader br = null;
try {
InputStreamReader isr = new InputStreamReader(System.in);
br = new BufferedReader(isr);
while (true) {
System.out.println("请输入字符串:");
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 {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
7. 打印流(PrintStream,PrintWriter)(处理流之四)
打印流:实现将基本数据类型的数据格式转化为字符串输出
提供了一系列重载的print()和println()方法
常用的println()就是打印流PrintStream中的方法,out的数据类型是PrintStream
通过setOut()设置输出流,将从控制台输出转化为文件输出
@Test
public void test2() {
PrintStream ps = null;
try {
FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\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();
}
}
}
8. 数据流(DataInputStream,DataOutputStream)(处理流之五)
为了方便地操作Java的基本数据类型和String的数据,可以使用数据流。
数据流有两个类:(用于读取和写出基本数据类型、String类的数据)
DataInputStream 和 DataOutputStream,分别“套接”在 InputStream 和 OutputStream 子类的流上
/*
1. 数据流
3.1 DataInputStream 和 DataOutputStream
3.2 作用:用于读取或写出基本数据类型的变量或字符串
练习:将内存中的字符串、基本数据类型的变量写出到文件中。
注意:处理异常的话,仍然应该使用try-catch-finally.
*/
//写入data.txt
@Test
public void test3() throws IOException {
//1.
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
//2.
dos.writeUTF("刘建辰");
dos.flush();//刷新操作,将内存中的数据写入文件
dos.writeInt(23);
dos.flush();
dos.writeBoolean(true);
dos.flush();
//3.
dos.close();
}
/*
将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。
*/
//读取data.txt
@Test
public void test4() throws IOException {
//1.
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
//2.
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);
//3.
dis.close();
}
注意点:
- 读取不同类型的数据的顺序要与当初写入文件时保存的数据的顺序一致
- flush():刷新操作就是将内存中的数据写入文件
9. 对象流(处理流之六)(重要)
ObjectInputStream和OjbectOutputSteam
用于存储和读取基本数据类型数据或对象的处理流。
对象流的强大之处是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来
9.1 对象的序列化机制
- 序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
- 反序列化:用ObjectInputStream类读取基本类型数据或对象的机制
注意:ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量
将对象序列化的优点:
- 可以将Java对象转化为与平台无关的二进制流,例如使用Windows系统传输对象流给Linux系统,Linux系统也能够使用对象流读取出对象的数据。
- 序列化为二进制流之后,可以将数据存储在磁盘上或者通过网络传输
序列化
/*
序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
使用ObjectOutputStream实现
*/
@Test
public void testObjectOutputStream(){
ObjectOutputStream oos = null;
try {
//1.
oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
//2.
oos.writeObject(new String("我爱北京天安门"));
oos.flush();//刷新操作
oos.writeObject(new Person("王铭",23));
oos.flush();
oos.writeObject(new Person("张学良",23,1001,new Account(5000)));
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(oos != null){
//3.
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
反序列化
/*
反序列化:将磁盘文件中的对象还原为内存中的一个java对象
使用ObjectInputStream来实现
*/
@Test
public void testObjectInputStream(){
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("object.dat"));
Object obj = ois.readObject();
String str = (String) obj;
Person p1 = (Person) ois.readObject();
Person p2 = (Person) ois.readObject();
System.out.println(str);
System.out.println(p);
System.out.println(p1);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(ois != null){
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
9.2 自定义类实现序列化
自定义类实现序列化需要:
- 实现Serializable接口
Serializable接口中什么都没有,是一个标识接口 - 提供一个全局变量,serialVersionUID
public static final long serialVersionUID = 475463534532L;
- 除了当前Person类需要实现Serializable接口之外,还必须保证其内部所有属性也必须是可序列化的。
- 默认情况下,基本数据类型可序列化
- Person类中出现自定义类也要是可序列化的,如Account类的对象
**补充:**ObjectOutputStream和ObjectInputStream不能序列化static和transient(暂时的,短暂的)修饰的成员变量
public class Person implements Serializable {
//serialVersionUID
public static final long serialVersionUID = 475463534532L;
private String name;
private int age;
private int id;
private Account acct;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name, int age, int id) {
this.name = name;
this.age = age;
this.id = id;
}
public Person(String name, int age, int id, Account acct) {
this.name = name;
this.age = age;
this.id = id;
this.acct = acct;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", id=" + id +
", acct=" + acct +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
serialVersionUID
serialVersionUID的作用:在反序列化时,我们接收到一串二进制信息,我们将二进制信息对象中的serialVersionUID与类的serialVersionUID比较。如果两者的serialVersionUID是一致的,我们就能确认是这个类的对象。
需要显式地声明serialVersionUID,否则系统会默认生成,对类的修改后可能会导致UID不一致的问题。
补充
序列化的概念很重要,在信息的传输中信息都需要是可序列化的。
一般在传输过程中会使用.json文件,.json格式的文件中保存的是都是字符串,而字符串本身是可序列化的。
10. 随机存取文件流 RandomAccessFile
RandomAccessFile 声明在java.io包下,但直接继承于java.lang.Object类。并且它实现了DataInput、DataOutput这两个接口,也就意味着这个类既可以读也可以写。
RandomAccessFile 类支持 “随机访问” 的方式,程序可以直接跳到文件的任意地方来读、写文件
- 支持只访问文件的部分内容
- 可以向已存在的文件后追加内容
RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。
RandomAccessFile 类对象可以自由移动记录指针:
- long getFilePointer():获取文件记录指针的当前位置
- void seek(long pos):将文件记录指针定位到 pos 位置
RandomAccessFile既可作为输出流,也可以作为输入流
@Test
public void test1() {
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
//1.
raf1 = new RandomAccessFile(new File("爱情与友情.jpg"),"r");
raf2 = new RandomAccessFile(new File("爱情与友情1.jpg"),"rw");
//2.
byte[] buffer = new byte[1024];
int len;
while((len = raf1.read(buffer)) != -1){
raf2.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//3.
if(raf1 != null){
try {
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(raf2 != null){
try {
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
如果RandomAccessFile作为输出流时,
- 如果写出到的文件不存在,则在执行过程中自动创建。
- 如果写出到的文件存在,则会对原有文件内容进行覆盖。(如果没有指定文件指针时,默认从头覆盖)
@Test
public void test2() throws IOException {
RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");
raf1.write("xyz".getBytes());
raf1.close();
}
seek(long pos)设置文件指针的位置
@Test
public void test2() throws IOException {
RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");
//将文件指针调到角标为3的位置
//当前代码是从角标为3的位置开始覆盖
raf1.seek(3);
raf1.write("xyz".getBytes());
raf1.close();
}
RandomAccessFile实现插入操作(不覆盖)
使用StringBuilder存储插入位置后面的内容
@Test
public void test3() throws IOException {
RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");
//将指针调到角标为3的位置
raf1.seek(3);
//指定StringBuilder初始数组的长度
StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
//添加指针3后面的所有数据到StringBuilder中
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());
raf1.close();
//思考:将StringBuilder替换为ByteArrayOutputStream
}
11. NIO、NIO.2
NIO是在jdk4提出的,NIO.2是在jdk7提出的
NIO.2逐渐正在替代IO,在框架中可以看到NIO的使用
待补充……
12 使用第三方jar包中的API
在实际开发中可以直接使用第三方写好的API,向复制文件等操作可以不用自己使用流编写,而是调用.jar包中的方法
- 在IDEA的模块下新建一个Directory,命名为libs
- 将.jar包复制到该目录下
- 将.jar右击add As Library
- 然后就可以使用.jar中的API了
使用FileUtil中的copyFile()方法实现文件复制
public static void main(String[] args) {
File srcFile = new File("day10\\爱情与友情.jpg");
File destFile = new File("day10\\爱情与友情2.jpg");
try {
FileUtils.copyFile(srcFile,destFile);
} catch (IOException e) {
e.printStackTrace();
}
}