package cn.yhy.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;
class CopyUtil {
private CopyUtil() {
}
public static boolean fileExists(String path) { // 判断源文件是否存在
return new File(path).exists();
}
public static void creatParentDirectory(String path) { // 创建目标路径
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
}
public static boolean copy(String srcPath, String desPath) {
boolean flag = false;
File inFile = new File(srcPath);
File outFile = new File(desPath);
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(inFile);
output = new FileOutputStream(outFile);
copyHandle(input, output);
flag = true;
} catch (Exception e) {
flag = false;
} finally {
try {
input.close();
output.close();
} catch (Exception e) {
}
}
return flag;
}
private static void copyHandle(InputStream input, OutputStream output) throws IOException {
long start = System.currentTimeMillis();
int temp = 0;
do {
temp = input.read();
output.write(temp);
} while (temp != -1);
long end = System.currentTimeMillis();
System.out.println("【统计】拷贝文件花费时间:" + (end - start));
}
}
public class Copy {
public static void main(String args[]) {
if (args.length != 2) {
System.out.println("错误的运行方式! 拷贝格式按照 java Copy 源文件路径 目标文件路径");
System.exit(1);
}
if (CopyUtil.fileExists(args[0])) {
CopyUtil.creatParentDirectory(args[1]);
System.out.println(CopyUtil.copy(args[0], args[1]) ? "拷贝已顺利完成" : "拷贝失败!");
} else {
System.out.println("拷贝未完成,源文件路径不存在!");
}
}
}
首次独立完成文件拷贝操作,【do{}while();】 及拷贝时间待优化
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.