文件的读写
介绍两种文件的读写方式,一种是字节流的,一种使用缓冲池。
先说第一种,上代码
import lombok.extern.slf4j.Slf4j;
import java.io.*;
/**
* 字节流
*/
@Slf4j
public class FileStream {
public static void main(String[] args) {
File file = new File("C:/Users/Administrator/Desktop/5f2bb5eb2c896.jpg");
try {
fileWriteStream(file);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 以字节流的形式读写文件,将内容复制到指定文件
* @param file 原文件
* @throws IOException
*/
public static void fileWriteStream(File file) throws IOException {
File fileNew = new File("C:/Users/Administrator/Desktop/5.jpg");
if (fileNew.exists()){
fileNew.delete();
}
long start = System.currentTimeMillis();
if (file.exists()){
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(fileNew);
byte[] bytes = new byte[2<<10];
int read;
while ((read = fileInputStream.read(bytes))!=-1){
for (int i=0;i<read;i++){
fileOutputStream.write(bytes[i]);
}
}
log.info("文件写入成功");
fileOutputStream.close();
fileInputStream.close();
}else {
log.info("文件不存在");
}
long end = System.currentTimeMillis();
log.info("读写耗时:"+(end-start)+"毫秒");
}
}
使用字节流是可以读写图片视频等文件的,但是使用字符流(这里没介绍)是不能读写图片视频的。
还有一种使用缓冲池的
import lombok.extern.slf4j.Slf4j;
import java.io.*;
/**
* 用缓冲池来进行文件读写操作,会更高效
*/
@Slf4j
public class BufferStream {
public static void main(String[] args) {
File file = new File("C:/Users/Administrator/Desktop/5f2bb5eb2c896.jpg");
try {
bufferInOut(file);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 使用缓存池进行文件复制
* @param file 原文件
* @throws IOException
*/
public static void bufferInOut(File file) throws IOException {
File fileNew = new File("C:/Users/Administrator/Desktop/5.jpg");
if (fileNew.exists()){
boolean delete = fileNew.delete();
log.info(delete?"存在同名文件,已删除":"存在同名文件,尝试删除失败");
}
//开始时间
long start = System.currentTimeMillis();
if (file.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(fileNew);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
byte[] bytes = new byte[2<<8];
int read;
while ((read = bufferedInputStream.read(bytes))!=-1){
for (int i=0;i<read;i++){
bufferedOutputStream.write(bytes[i]);
}
}
log.info("文件复制完成");
bufferedOutputStream.close();
bufferedInputStream.close();
fileOutputStream.close();
fileInputStream.close();
} else {
log.info("文件不存在");
}
long end = System.currentTimeMillis();
log.info("读写耗时:"+(end-start)+"毫秒");
}
}
相较于前者,使用缓冲池读写效率更快。读写小文件可能没啥感觉,一般会快十倍左右。