Java实现文件的拷贝有很多种方法,觉得晕乎乎的,不知道使用哪种方法好,进过一下午的学习,总结出三种常见的实现文件拷贝的方法,并且做了一个对比,看哪个方法能比较快速的实现文件拷贝。
一、单字节拷贝
/*
* 单字节拷贝,不带缓冲区
*/
public static void copyByByte(File srcFile,File descFile)throws IOException{
if(!srcFile.exists()){
throw new IllegalArgumentException("文件:"+srcFile+"不存在!");
}
if(!srcFile.isFile()){
throw new IllegalArgumentException(srcFile+"不是文件!");
}
FileInputStream in =new FileInputStream(srcFile);
FileOutputStream out = new FileOutputStream(descFile);
int a;
while((a=in.read())!=-1){
out.write(a);
out.flush();
}
in.close();
out.close();
}
二、带缓冲区的字节流
/*
* 利用带缓冲的字节流
*/
public static void copyByBuffer(File srcFile,File descFile)throws IOException{
if(!srcFile.exists()){
throw new IllegalArgumentException("文件:"+srcFile+"不存在!");
}
if(!srcFile.isFile()){
throw new IllegalArgumentException(srcFile+"不是文件!");
}
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(descFile));
int a;
while((a=bis.read())!= -1){
bos.write(a);
bos.flush();
}
bis.close();
bos.close();
}
三、批量处理
/*
* 批量拷贝
*/
public static void copyFile(File srcFile,File descFile)throws IOException{
if(!srcFile.exists()){
throw new IllegalArgumentException("文件:"+srcFile+"不存在!");
}
if(!srcFile.isFile()){
throw new IllegalArgumentException(srcFile+"不是文件!");
}
FileInputStream in = new FileInputStream(srcFile);
FileOutputStream out = new FileOutputStream(descFile);
/*从in中批量读取字节,放入到buf这个字节数组中,
* 从第0个位置开始放,最多放buf.length个
* 返回的是读到的字节的个数
*/
byte[] buf = new byte[8*1024];
int a;
while((a=in.read(buf,0,buf.length))!=-1){
out.write(a);
out.flush();
}
in.close();
out.close();
}
接下来,写一个测试方法,来测试一下三种方法拷贝文件的快慢。测试很简单,复制一首歌,大小为3.80MB。
public static void main(String[] args) {
try {
long start = System.currentTimeMillis();
CopyByByte.copyByByte(new File("C:\\Users\\LJH\\Desktop\\Twins-星光游乐园.mp3")
,new File("C:\\Users\\LJH\\Desktop\\Twins-星光游乐园(单字节拷贝).mp3"));
/*
* CopyByByte.copyByBuffer(new File("C:\\Users\\LJH\\Desktop\\Twins-星光游乐园.mp3")
,new File("C:\\Users\\LJH\\Desktop\\Twins-星光游乐园(单字节带缓冲区拷贝)).mp3"));
*/
/*
* CopyByByte.copyFile(new File("C:\\Users\\LJH\\Desktop\\Twins-星光游乐园.mp3")
,new File("C:\\Users\\LJH\\Desktop\\Twins-星光游乐园(批量拷贝)).mp3"));
*/
System.out.println();
long end = System.currentTimeMillis();
System.out.println(end - start);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
结果:
1、单字节拷贝时间(毫秒):
2、单字节带缓冲区拷贝时间(毫秒):
3、批量拷贝(毫秒):
从结果来看,单字节不适合用来读取或者拷贝大的数据,因为效率太低了,带缓冲区的单字节虽然快了一些,但还是太慢了点,而批量处理则快了很多很多,也是最常用的读取文件的方法。
注意点:
对文件进行操作,要注意抛出IO异常,防范于未然。
操作完文件(读、写操作),要关闭文件,养成好习惯。
当要使用缓冲区的时候,要注意需要刷新缓冲区(也就是flush()方法)。