IO流经常用在导入导出的操作
一、File类
以前的数组和集合都是把数据存储在内存中,但是没有持久化;
所有,我们可以用IO流把数据存储在磁盘,从而持久化。
创建对象的方法就是直接通过构造器 (new)
- public File(String pathname) :通过将给定的路径名字符串转换为抽象路径名来创建新的
File实例。 - public File(String parent, String child) :从父路径名字符串和子路径名字符串创建新
的 File实例。 - public File(File parent, String child) :从父抽象路径名和子路径名字符串创建新的
File实例。
这个文件路径无论存在与否,不存就无实际意义而已,不会报错。
路径是不区分大小写的。
拓展:
①为了实行路径的跨平台使用
路径分割符(在java代码中得是\,/这个是转义符) :File.separator
分号; :File.pathSeparator
eg: D:\test\test2.txt
String pathStr = “D:” + File.separator+“test”+ File.separator+“test2.txt”;
②绝对路径:从盘符开始的路径,这是一个完整的路径。
相对路径:相对于项目目录的路径,这是一个便捷的路径,开发中经常使用
常用方法
public String getAbsolutePath() :返回此File的绝对路径名字符串。
public String getPath() :将此File转换为路径名字符串。
public String getName() :返回由此File表示的文件或目录的名称。
public long length() :返回由此File表示的文件的长度。 不能获取目录的长度。
public boolean exists() :此File表示的文件或目录是否实际存在。
public boolean isDirectory() :此File表示的是否为目录。
public boolean isFile() :此File表示的是否为文件。
public boolean createNewFile() :当且仅当具有该名称的文件尚不存在时,创建一个新的空
文件。
public boolean delete() :删除由此File表示的文件或目录。(删除文件夹只能空的文件夹)
public boolean mkdir() :创建由此File表示的目录。(目录指的就是文件夹)
public boolean mkdirs() :创建由此File表示的目录,包括任何必需但不存在的父目录
public String[] list() :返回一个String数组,表示该File目录中的所有子文件或目录。
public File[] listFiles() :返回一个File数组,表示该File目录中的所有的子文件或目录
拓展
①遍历目录 就是用上面你都方法;
②递归
递归一定要有结束递归的条件;效率比循环低。
递归的实现逻辑:
Ⅰ.直接递归:方法A调用方法A
Ⅱ.间接递归:方法A调用方法B,方法B调用方法C,方法C调用方法A
二、IO流
IO流的分类
流 | 输入流(抽象类) | 用法 | 输出流(抽象类) | 用法 |
---|---|---|---|---|
字节流 | InputStram(File/path) | 用的是实现类FileInputStram的 read() | OutputStream(File/path) | 用的是实现类FileOutputStream的write() |
字符流 | Reader(File/path | 用的是实现类FileReader的 read() | Writer(File/path) | 用的是实现类FileWriter的 write() |
字节缓冲流 | BufferedInputStream(InputStram)(不是抽象类) | read() | BufferedOutputStream(OutputStream) (不是抽象类) | writer() |
字符缓冲流 | BufferedReader(Reader)(不是抽象类) | readLine() | BufferedWriter(Writer)(不是抽象类) | writer() |
注意事项
- IO流的创建给的路径假如没有文件,就会直接创建文件。但是文件夹一定得有要不然空指针报错的
- 输出流:从内存写出到硬盘(代码 -》文件) 出代码(内存)
- 输入流:从硬盘读取到内存(文件-》代码) 入代码(内存)
- 字节流:可以操作任何**(万能流)**
- 字符流:只能操作文本文档类型的文件
- 每一次输出流的操作,都是覆盖文件以前的数据,可以加个true来表示从后面你继续写
FileOutputStream outputStream = new FileOutputStream(file1, true); - 字符流,一定要关流,才会把数据输入输出
IO流的实操
字节流/字符流
- 对于字节流,把数字存入文件中,那就会自动转换成字符。
- 字符流,一定要关流,才会把数据输入输出。
- 对于字符流,可以输出输入多个字符,用字符数组cahr[]
- 对于字节流,可以输出输入多个字节,用字节数组byte[]
package com.example.demo002.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
public class test {
private static final Logger logger = LoggerFactory.getLogger(test.class);
public static void main(String[] args) {
File file1 = new File("D:\\study\\test1.txt");
String pathStr = "D:" + File.separator+"study"+ File.separator+"test2.txt";
File file2 = new File(pathStr);
System.out.println(file1.toString());
System.out.println(pathStr);
FileOutputStream outputStream = null;
FileInputStream inputStream = null;
FileReader reader = null;
FileWriter writer = null;
byte[] bytesLen = new byte[3];
try {
System.out.println("===========字节流==========");
// 1.字节流的使用
// 1.1字节输出流(内存到符盘),写入文件
outputStream = new FileOutputStream(file1, true);
// 1.2字节输入流(符盘到内存),读文件
inputStream = new FileInputStream(file1);
byte[] bytes = {97,98,99};
outputStream.write(65);
outputStream.write(bytes);
int read = inputStream.read(); // 默认读取第一个,返回的是对于的int类型
System.out.println("第一次读取:" + (char)read);
inputStream.read(bytesLen); // 按长度读取,并且存入byte数组
System.out.println("第二次读取:" + new String(bytesLen));
// 2.字符流
System.out.println("===========字符流==========");
writer = new FileWriter(file2);
reader = new FileReader(file2);
writer.write(97);
int read2 = reader.read();
System.out.println("第一次读取" + (char)read2);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
inputStream.close();
writer.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
D:\study\test1.txt
D:\study\test2.txt
=字节流
15:39:06.668 [main] INFO com.example.demo002.service.test - 开始开启IO流
第一次读取:A
第二次读取:abc
15:39:06.670 [main] INFO com.example.demo002.service.test - io流开启成功
=字符流
第一次读取a
缓冲流
BufferedOutputStream outputStream = new BufferedOutputStream(new
FileOutputStream(file));
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
对于字符缓冲
输出流BufferedWriter,有一个newLine()方法,表示换行。
输入流BufferedReader,有一个readLine()方法,读取一行文字,最后读不出来返回null
转换流
只对文本文档(没有图片的文档,所以word不行)有用
InputStreamReader ,字节流到字符流
是Reader的子类,是从字节流到字符流的桥梁。它读取字,并使用指定的字符集将其解码为字符。
- 构造方法
InputStreamReader(InputStream in) : 创建一个使用默认字符集的字符流。
InputStreamReader(InputStream in, String charsetName) : 创建一个指定字符集的字符
流。
public class ReaderDemo2 {
public static void main(String[] args) throws IOException {
// 定义文件路径,文件为gbk编码
String FileName = "E:\\file_gbk.txt";
// 创建流对象,默认UTF8编码
InputStreamReader isr = new InputStreamReader(new
FileInputStream(FileName));
// 创建流对象,指定GBK编码
InputStreamReader isr2 = new InputStreamReader(new
FileInputStream(FileName) , "GBK");
// 定义变量,保存字符
int read;
// 使用默认编码字符流读取,乱码
while ((read = isr.read()) != -1) {
System.out.print((char)read); // ��Һ�
}
isr.close();
// 使用指定编码字符流读取,正常解析
while ((read = isr2.read()) != -1) {
System.out.print((char)read);// 大家好
}
isr2.close();
}
}
OutputStreamWriter 从字符流到字节流
是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符编码为字节。它的字符集可以由名称指定,也可以接受平台的默认字符集。
- 构造方法
OutputStreamWriter(OutputStream in) : 创建一个使用默认字符集的字符流。
OutputStreamWriter(OutputStream in, String charsetName) : 创建一个指定字符集的字符
流。
public class OutputDemo {
public static void main(String[] args) throws IOException {
// 定义文件路径
String FileName = "E:\\out.txt";
// 创建流对象,默认UTF8编码
OutputStreamWriter osw = new OutputStreamWriter(new
FileOutputStream(FileName));
// 写出数据
osw.write("你好"); // 保存为6个字节
osw.close();
// 定义文件路径
String FileName2 = "E:\\out2.txt";
// 创建流对象,指定GBK编码
OutputStreamWriter osw2 = new OutputStreamWriter(new
FileOutputStream(FileName2),"GBK");
// 写出数据
osw2.write("你好");// 保存为4个字节
osw2.close();
}
}
序列化流
Java 提供了一种对象序列化的机制。用一个字节序列可以表示一个对象,该字节序列包含该 对象的数
据 、 对象的类型 和 对象中存储的属性 等信息。字节序列写出到文件之后,相当于文件中持久保存了一个对象的信息。反之,该字节序列还可以从文件中读取回来,重构对象,对它进行反序列化。 对象的数据 、 对象的类型和 对象中存储的数据 信息,都可以用来在内存中创建对象。看图理解序列化:
ObjectOutputStream类
将Java对象的原始数据类型写出到文件,实现对象的持久存储
-
构造方法
public ObjectOutputStream(OutputStream out) : 创建一个指定OutputStream的
ObjectOutputStream。 -
序列化操作
- 一个对象要想序列化,必须满足两个条件:
该类必须实现 java.io.Serializable 接口, Serializable 是一个标记接口,不实现此接口的
类将不会使任何状态序列化或反序列化,会抛出 NotSerializableException 。
该类的所有属性必须是可序列化的。如果有一个属性不需要可序列化的,则该属性必须注明是瞬态
的,使用 transient 关键字修饰。
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int age; // transient瞬态修饰成员,不会被序列化
public void addressCheck() {
System.out.println("Address check : " + name + " -- " + address);
}
}
2.写出对象方法
- public final void writeObject (Object obj) : 将指定的对象写出。
public class SerializeDemo{
public static void main(String [] args) {
Employee e = new Employee();
e.name = "zhangsan";
e.address = "beiqinglu";
e.age = 20;
try {
// 创建序列化流对象
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("employee.txt"));
// 写出对象
out.writeObject(e);
// 释放资源
out.close();
fileOut.close();
System.out.println("Serialized data is saved"); // 姓名,地址被序列化,
年龄没有被序列化。
} catch(IOException i) {
i.printStackTrace();
}
}
}
输出结果:
Serialized data is saved
ObjectInputStream类
ObjectInputStream反序列化流,将之前使用ObjectOutputStream序列化的原始数据恢复为对象。
- 构造方法
public ObjectInputStream(InputStream in) : 创建一个指定InputStream的
ObjectInputStream。 - 反序列化操作1
如果能找到一个对象的class文件,我们可以进行反序列化操作,调用 ObjectInputStream 读取对象的
方法:
public final Object readObject () : 读取一个对象。
public class DeserializeDemo {
public static void main(String [] args) {
Employee e = null;
try {
// 创建反序列化流
FileInputStream fileIn = new FileInputStream("employee.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
// 读取一个对象
e = (Employee) in.readObject();
// 释放资源
in.close();
fileIn.close();
}catch(IOException i) {
// 捕获其他异常
i.printStackTrace();
return;
}catch(ClassNotFoundException c) {
// 捕获类找不到异常
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
// 无异常,直接打印输出
System.out.println("Name: " + e.name); // zhangsan
System.out.println("Address: " + e.address); // beiqinglu
System.out.println("age: " + e.age); // 0
}
}
对于JVM可以反序列化对象,它必须是能够找到class文件的类。如果找不到该类的class文件,则抛出
一个 ClassNotFoundException 异常。
- 反序列化操作2
另外,当JVM反序列化对象时,能找到class文件,但是class文件在序列化对象之后发生了修改,那么
反序列化操作也会失败,抛出一个 InvalidClassException 异常。发生这个异常的原因如下:
- 该类的序列版本号与从流中读取的类描述符的版本号不匹配
- 该类包含未知数据类型
- 该类没有可访问的无参数构造方法
Serializable 接口给需要序列化的类,提供了一个序列版本号。 serialVersionUID 该版本号的目
的在于验证序列化的对象和对应类是否版本匹配。
public class Employee implements java.io.Serializable {
// 加入序列版本号
private static final long serialVersionUID = 1L;
public String name;
public String address;
// 添加新的属性 ,重新编译, 可以反序列化,该属性赋为默认值.
public int eid;
public void addressCheck() {
System.out.println("Address check : " + name + " -- " + address);
}
}