import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 建立一个专门负责文件拷贝处理的类,该类具备的功能如下:
* 1、判断需要拷贝的源文件是否存在;
* 2、判断目标文件父路径是否存在,如果不存在这应该创建
* 3、需要进行文件拷贝操作的处理。
* @author ZZ
*
*/
class CopyUtil{ //这个类不需要保存任何的属性,所以将它的构造方法私有化,使用static方法。
private CopyUtil(){} //构造方法私有化
/**
* 判断要拷贝的路径是否存在
* @param path 源文件路径
* @return 如果存在返回 true,否则返回false
*/
public static boolean fileExists(String path){
return new File(path).exists();
}
/**根据传入的路径判断目标文件父路径是否存在,不存在则创建
* @param path 目标文件路径,通过此路径获得父路径
*/
public static void createParentDirectory(String path){
File file=new File(path);
if(!file.isDirectory()){
file.getParentFile().mkdirs();
}
}
/**
* 进行文件拷贝操作
* @param strPath 源文件路径
* @param desPath 目标文件路径
* @return 文件拷贝成功返回true,失败返回false。
* @throws IOException
* @throws Exception
*/
public static boolean copy(String strPath,String desPath) throws IOException {
boolean flag=false;
File inFile=new File(strPath);
File outFile=new File(desPath);
OutputStream output=null;
InputStream input =null;
try {
output=new FileOutputStream(outFile);
input =new FileInputStream(inFile);
copyHandle(input, output); //完成具体的文件拷贝处理
flag=true;
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return flag;
}
/**
* 实现具体的文件拷贝操作
* @param input 输入流对象
* @param output 输出流对象
*/
private static void copyHandle(InputStream input,OutputStream output) throws IOException{
//InputStream有一个读取单个字节的方法:int read();
//OutputStream有一个输出单个字节的方法:void write(int data)
long statr=System.currentTimeMillis();
byte[] data=new byte[8192];
int temp=0;
// do {
// temp=input.read(); //读取单个字节
// output.write(temp); //写入单个字节
// } while (temp!=-1); //如果有数据继续读
while((temp=input.read(data))!=-1){
output.write(data,0,temp);
}
long end=System.currentTimeMillis();
System.out.println("拷贝数据消耗的时间为:"+(end-statr)/1000);
}
}
/*---------------------------------------Copy类------------------------------------------*/
public class Copy {
public static void main(String[] args) throws IOException {
if(args.length!=2){ //判断参数是否为2个
System.out.println("错误的执行方式,命令调用:java copy 源文件路径 目标文件路径");
System.exit(1); //系统退出
}
if(CopyUtil.fileExists(args[0])){ //必须判断文件是否存在
CopyUtil.createParentDirectory(args[1]); //创建目标父目录
//进行拷贝工作
System.out.println(CopyUtil.copy(args[0], args[1])?"文件拷贝成功":"文件拷贝失败");
}else{
System.out.println("文件不存在");
}
}
}