1、工具类
package com.imooc.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOUtil {
/**
* 文件拷贝,字节批量读取
* @param srcFile
* @param destFile
* @throws IOException
*/
public static void copyFile(File srcFile,File destFile)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(destFile);
byte[] buf = new byte[8*1024];
int b ;
while((b = in.read(buf,0,buf.length))!=-1){
out.write(buf,0,b);
out.flush();//最好加上
}
in.close();
out.close();
}
/**
* 进行文件的拷贝,利用带缓冲的字节流
* @param srcFile
* @param destFile
* @throws IOException
*/
public static void copyFileByBuffer(File srcFile,File destFile)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(destFile));
int c ;
while((c = bis.read())!=-1){
bos.write(c);
bos.flush();//刷新缓冲区
}
bis.close();
bos.close();
}
/**
* 单字节,不带缓冲进行文件拷贝
* @param srcFile
* @param destFile
* @throws IOException
*/
public static void copyFileByByte(File srcFile,File destFile)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(destFile);
int c ;
while((c = in.read())!=-1){
out.write(c);
out.flush();
}
in.close();
out.close();
}
}
2、测试结果
package com.imooc.io;
import java.io.File;
import java.io.IOException;
public class IOUtilTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
long start = System.currentTimeMillis();
/*IOUtil.copyFileByByte(new File("e:\\javaio\\1.mp3"), new File(
"e:\\javaio\\2.mp3"));*/ //两万多毫秒
/*IOUtil.copyFileByBuffer(new File("e:\\javaio\\1.mp3"), new File(
"e:\\javaio\\3.mp3"));//一万多毫秒*/
IOUtil.copyFile(new File("e:\\javaio\\1.mp3"), new File(
"e:\\javaio\\4.mp3"));//7毫秒
long end = System.currentTimeMillis();
System.out.println(end - start );
} catch (IOException e) {
e.printStackTrace();
}
}
}
字节读取复制:两万多毫秒
缓存字节流:一万多毫秒
字节批量读取:7毫秒