目录
IO流的概念
存取和读取数据的方案,可以用来对数据进行读取
IO流分类
流的方向
输出流:写
输入流:读
操作文件类型
字节流:所有文件类型
字符流:纯文本文件
文件字节输出流FileOutputStream
字节输出流细节
例子:FileOutputStream文件字节输出流
创建字节输出流对象
细节1: 参数是字符串表示的路径或者File对象都是可以的
细节2:如果文件不存在会创建一个新的文件,但是要保证父级路径是存在的
细节3:如果文件已经存在,则会清空文件
写数据
细节: write方法的参数是整数,但是实际上写到本地文件中的是整数在ASCII上对应的字符
释放资源
细节:每次使用完流之后都要释放资源
字节输出流的三种写数据方式
public static void main(String[] args) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream("D:\\本地项目\\IO流\\a.txt");
byte[] bytes = {97, 98, 99};
//从0索引位置开始读取,读取2个长度的数据
fileOutputStream.write(bytes, 0, 2);
fileOutputStream.close();
}
小tips:在不同系统中的换行符
Windows:\r\n
mac:\r
Linux:\n
案例:实现在原文件中追加“今天天气真好”,并且是换行添加
public static void main(String[] args) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream("D:\\本地项目\\IO流\\a.txt",true);
String str="\r\n今天天气真好";
fileOutputStream.write(str.getBytes());
fileOutputStream.close();
}
文件字节输入流FileInputStream
创建字节输入流对象
如果文件不存在,就直接报错。
读取数据
一次读一个字节,读出来的是数据在ASCII上对应的数字细节2:读到文件末尾了,read方法返回-1。
释放资源
每次使用完流必须要释放资源
循环读取文件数据
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\本地项目\\IO流\\a.txt");
int b=0;
while((b=fis.read())!=-1){
System.out.println((char) b);
}
fis.close();
}
大文件拷贝
public static void main(String[] args) throws IOException {
//大文件拷贝
FileInputStream fis = new FileInputStream("D:\\本地项目\\IO流\\a.mp4");
FileOutputStream fos = new FileOutputStream("D:\\本地项目\\IO流\\b.mp4");
//实现大文件传输实现最重要的就是读从byte数组里面
byte[] bytes=new byte[1024*1024*5];
int len = 0;
long start = System.currentTimeMillis();
while ((len=fis.read(bytes))!=-1){
fos.write(bytes,0,len);
}
long end = System.currentTimeMillis();
System.out.println(end-start);
fos.close();
fis.close();
}
一个英文占一个字节,二进制第一位是0(0110 0111)
一个中文占两个字节,二进制高位字节的第一位是1(10111011 10000110)
GBK中中文占2个字节
UTF8中中文占三个字节
指定UTF8格式:StandardCharsets.UTF_8
File类
listFiles() | 获取文件列表 |
isFile() | 判断是否未文件 |
mkdir() | 创建文件夹(创建多目录的文件夹需要使用mkdirs()) |
createNewFile() | 创建文件 |
delete() | 删除文件 |
案例一:拷贝一个文件夹,考虑子文件夹
import java.io.*;
public class FileTest {
public static void main(String[] args) throws IOException {
File src=new File("C:\\Users\\lyt\\Desktop\\a");
File dest=new File("C:\\Users\\lyt\\Desktop\\d");
copyFiles(src,dest);
}
private static void copyFiles(File src, File dest) throws IOException {
dest.mkdir();
File[] files = src.listFiles();
for (File file : files) {
if (file.isFile()){
//是文件
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(new File(dest,file.getName()));
byte[] bytes = new byte[1024];
int len=0;
while ((len=fis.read(bytes))!=-1) {
fos.write(bytes,0,len);
}
fos.close();
fis.close();
}else {
//递归
copyFiles(file,new File(dest,file.getName()));
}
}
}
}
缓冲流
注意:BufferReader有一个方法是readLine()可以读一行的数据
压缩流和解压缩流
ZipInputStream和ZipOutputStream
工具类Commons-io
导入依赖
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>