几种基于javaI/O的文件拷贝操作比较

时间:2023-12-17 10:29:08

最近公司的项目用到文件拷贝,由于涉及到的大量大文件的拷贝工作,代码性能问题显得尤为重要,所以写了以下例子对几种文件拷贝操作做一比较:

0、文件拷贝测试方法

 public static void fileCopy(String source, String target,int type) {
Date start = new Date();
File in = null;
File out = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
in = new File(source);
out = new File(target);
switch (type) {
case 1:
copyer1(in, out, fis, fos);
break;
case 2:
copyer2(in, out, fis, fos);
break;
case 3:
copyer3(in, out, fis, fos);
break;
case 4:
copyer4(in, out, fis, fos);
break;
default:
break;
}
} catch (Exception 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();
}
}
Date end = new Date();
System.out.println("方法"+type+"用时:"+(end.getTime() - start.getTime())+" ms!");
}
}

方式一:一次读取全部数据

     /**
* 一次全部读取文件内容
*/
@SuppressWarnings("resource")
public static void copyer1(File in,File out,FileInputStream fis,FileOutputStream fos) throws IOException{
fis = new FileInputStream(in);
int size = fis.available();
byte[] buffer = new byte[size];
fis.read(buffer);
fos = new FileOutputStream(out);
fos.write(buffer);
fos.flush();
}

方式二:每次读入固定字节的数据

     /**
* 每次读取固定字节的数据
*/
@SuppressWarnings("resource")
public static void copyer2(File in,File out,FileInputStream fis,FileOutputStream fos) throws IOException{ fis = new FileInputStream(in);
fos = new FileOutputStream(out);
byte[] buffer = new byte[1024];
while (fis.read(buffer) != -1) {
fos.write(buffer);
}
fos.flush();
}

方式三:每次读取一行数据,适合按行解析数据的场景

     /**
* 每次读取一行数据
*/
@SuppressWarnings("resource")
public static void copyer3(File in,File out,FileInputStream fis,FileOutputStream fos) throws IOException{ fis = new FileInputStream(in);
fos = new FileOutputStream(out);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
fos.write(line.getBytes());
}
fos.flush();
}

方式四:每次读取一个字符,~_~,想想都累

     /**
* 每次读取一个字节
*/
@SuppressWarnings("resource")
public static void copyer4(File in,File out,FileInputStream fis,FileOutputStream fos) throws IOException{ fis = new FileInputStream(in);
fos = new FileOutputStream(out);
int i = 0;
while ((i = fis.read()) != -1) {
fos.write(i);
}
fos.flush();
}
}

最后:测试用main函数

     public static void main(String[] args) {
String source = "e:\\in.txt";
String target = "e:\\out.txt";
for (int i = 1; i < 5; i++) {
fileCopy(source, target, i);
}
}

测试文件:

几种基于javaI/O的文件拷贝操作比较

运行结果:
几种基于javaI/O的文件拷贝操作比较