一、概述
1、分类
- 按流的方向
- 输入流:数据流向是,从数据源到程序(以InputStream、Reader结尾)
- 输出流:数据流向是,从程序到目的地(以OutputStream、Writer结尾)
2.按处理的数据单元
- 字节流:以字节为单位,获取数据(以Stream结尾)
- 字符流:以字符为单位,获取数据(以Reader、Writer结尾)
3.按处理对象
- 节点流:可以直接从数据源或目的地读取数据
- 处理流:不能直接连接到数据或目的地,是处理流的流(BufferedInputStream、BufferedReader)
2、File类
方法:
- 创建对象,指向一个文件或文件夹:File file = new File("全路径");
- 获取文件或文件夹名:file.getName()
- 文件大小:file.length()
- 是否存在:file.exists()
- 绝对路径:file.getAbsoulutePath()
- 相对路径:file.getPath()
- 判断File是不是文件夹:file.isDirectory()
- 是不是文件:file.isFile()
- 是不是隐藏文件或文件夹:file.isHidden()
- 最后编辑时间:file.lastModified()
- 删除文件或文件夹:file.delete()
- 创建文件:file.createNewFile()
- 创建文件夹:file.mkdirs()
二、文件流
1、文件字节流
FileInputStream、FileOutputStream
2、文件字符流
FileReader、FileWriter
三、缓冲流
BufferedInputStream、BufferedOutputStream
BufferedReader、BufferedWriter
四、数据流和对象流
1、数据流:DataInputStream、DataOutputStream
2、对象流:ObjectInputStream、ObjectOutputStream
3、序列化与反序列化:
- 序列化:Serialization 将对象的状态信息转换为可以存储或传输的形式的过程。
对象(内存)------->字节数组 字节序列(外存、网络) - 反序列化:DeSerialization字节数组 字节序列(外存、网络)----------->对象(内存)
4、其他流
- 打印流:只有输出流,没有输入流
- 转换流:InputStreamReader、OutputStreamWriter
实现字节流到字符流的转换,是适配器设计模式的应用。 - 字节数组流:是节点流,数据源是字节数组,可以实现各种基本和引用数据类型与字节数组之间的相互转换。
5、复制文件夹(代码题)
import java.io.*;
/*
要求:复制文件夹
思路:需要2个路径(源文件,目标文件位置)
*/
public class Homework2_4 {
public static void main(String[] args) {
copyDirectory("E:\\腾讯游戏\\Download", "E:/Download");
}
private static void copyDirectory(String sourceDir, String desDir) {
//判断目标位置是否存在与desDir文件
File sourceFile = new File(sourceDir);
File desFile = new File(desDir);
if (!desFile.exists()) {
//如果不存在,就创建文件夹
desFile.mkdir();
}
//遍历源文件夹,获取其子文件
File[] files = sourceFile.listFiles();
for (File file : files) {
//判断源是文件还是文件夹
if (file.isDirectory()) {
//是文件夹,就在目标文件夹下创建一个同名文件夹
copyDirectory(file.getAbsolutePath(), desDir + "/" + file.getName());
} else {
//是文件,就进行复制
copyFile(file.getAbsolutePath(), desDir + "/" + file.getName());
}
}
}
/**
* 复制文件
*
* @param absolutePath 源文件位置
* @param desFile 目标文件位置
*/
private static void copyFile(String absolutePath, String desFile) {
//创建输入、输出流
try (
FileInputStream fis = new FileInputStream(new File(absolutePath));
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desFile));
) {
//读取文件
byte[] bytes = new byte[8192];
int length = bis.read(bytes);
while ((length=bis.read(bytes))!=-1){
//写入到目标文件
bos.write(bytes, 0, length);
}
bis.close();
bos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}