IO编程 文件拷贝代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Test1 {
public static void main(String[] args) throws Exception {
if(args.length!=2) {
System.out.println("命令执行错误,执行结构:java JAVAAPIDEMO 拷贝源文件路径 拷贝目标文件路径");
System.exit(1);
}
long start=System.currentTimeMillis();
FileUtil fu=new FileUtil(args[0],args[1]);
System.out.println(fu.copy()?"文件拷贝成功":"文件拷贝失败");
long end=System.currentTimeMillis();
System.out.println("拷贝完成的时间:"+(end-start));
}
}
class FileUtil{
private File srcFile;
private File desFile;
public FileUtil(File srcFile,File desFile) {
this.desFile =desFile;
this.srcFile =srcFile;
}
public FileUtil(String src, String des) {
this(new File(src),new File(des));
}
public boolean copy() throws Exception {//文件的拷贝处理
if(!this.srcFile.exists()) {
System.out.println("要拷贝的源文件不存在");
return false;
}
if(!this.desFile.getParentFile().exists()) {
this.desFile.getParentFile().mkdirs();
}
byte data[]=new byte[1024];
InputStream input=null;
OutputStream out=null;
try { input = new FileInputStream(this.srcFile);
out = new FileOutputStream(this.desFile);
int len=0;
while((len=input.read(data))!=-1) {
out.write(data,0,len);
}
} catch (Exception e) {
// TODO: handle exception
}finally {
if(input!=null) {
input.close();
}if(out!=null) {
out.close();
}
}
return true;
}
public void copyFileImpl(File srcFile,File desFile) throws Exception {
byte data[]=new byte[1024];
InputStream input=null;
OutputStream out=null;
try { input = new FileInputStream(this.srcFile);
out = new FileOutputStream(this.desFile);
int len=0;
while((len=input.read(data))!=-1) {
out.write(data,0,len);
}
} catch (Exception e) {
throw e;
}finally {
if(input!=null) {
input.close();
}if(out!=null) {
out.close();
}
}
}
}