使用字节流复制文件

时间:2022-01-24 20:59:03
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class Hello{
public static void main(String args[]) throws Exception{
String sourceFile
= "D:" + File.separator + "Manor.jpg";
String targetFile
= "D:" + File.separator + "copy.jpg";
File infile
= new File(sourceFile);
File outfile
= new File(targetFile);
copy(infile,outfile);
}
/**
* 文件拷贝操作
*
@param infile
*
@param outfile
*
@return
*
@throws Exception
*/
public static boolean copy(File infile,File outfile) throws Exception{
InputStream input
= null;
OutputStream output
= null;
try{
long start = System.currentTimeMillis();
if(!outfile.getParentFile().exists()){
outfile.getParentFile().mkdirs();
}
input
= new FileInputStream(infile);
output
= new FileOutputStream(outfile);
int temp = 0 ;
while((temp = input.read()) != -1){
output.write(temp);
}
long end = System.currentTimeMillis();
System.out.println(
"花费时间:" + (end - start));
return true;
}
catch (Exception e){
throw e;
}
finally{
if(input != null){
input.close();
}
if(output != null){
output.close();
}
}

}
}

 改进代码,使用字节数组,更快

public static boolean copy(File infile,File outfile) throws Exception{
InputStream input
= null;
OutputStream output
= null;
try{
long start = System.currentTimeMillis();

byte data[] = new byte[2048];
input
= new FileInputStream(infile);
output
= new FileOutputStream(outfile);
int temp = 0;
while((temp = input.read(data)) != -1){
output.write(data,
0,temp);
}

long end = System.currentTimeMillis();
System.out.println(
"花费时间:" + (end - start)/(double)1000 + "秒");
return true;
}
catch (Exception e){
throw e;
}
finally{
if(input != null){
input.close();
}
if(output != null){
output.close();
}
}

}