package demo;
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 CopyDemo{
public static void main(String[] args) throws IOException {
if(args.length != 2) {
System.out.println("参数输入错误");
System.exit(1); //退出
}
CopyUtil cp = new CopyUtil(args[0], args[1]);
long start = System.currentTimeMillis();//操作开始时间
System.out.println(cp.copy() ? "拷贝结果:成功" :"拷贝结果:失败");
long end = System.currentTimeMillis(); //结束时间
System.out.println("操作时长:" + (end - start));
}
}
class CopyUtil{//拷贝操作类
public File srcFile; //源文件路径
public File recFile; //目标路径
public CopyUtil(String src, String rec) {
this(new File(src), new File(rec));
}
public CopyUtil(File srcFile,File recFile){
this.srcFile = srcFile;
this.recFile = recFile;
}
public boolean copy() throws IOException{
if (!this.srcFile.getParentFile().exists()) {
System.out.println("源文件不存在");
return false;
}
if (!this.recFile.getParentFile().exists()) {//目标路径不存在
this.recFile.getParentFile().mkdirs();
}
InputStream in = new FileInputStream(srcFile); //新建读取源文化的输入流
OutputStream out = new FileOutputStream(recFile); //新建目标路径写入流
byte data[] = new byte[1024]; //新建一个缓存流
int len=0; //读取的数据长度
try {
while((len = in.read(data)) != -1 ){
out.write(data,0,len);
System.out.println("拷贝ok*****");
}
return true;
}catch (Exception e) {
throw e;
}finally {
//关闭流
if(out != null){
out.close();
}
if(in != null){
in.close();
}
}
}
}
[](https://www.yuque.com/docs/share/6a2ffcb8-6afb-49e4-b8bc-6ccebb551231?# 《咨询用文档》?%ra=link)
你是怎么输入参数的呢,输入要2个斜杠,如:
d:\\test.txt
或者
d:/test.txt