利用输入输出流实现文件的拷贝操作。将源文件地址与目标地址作为参数传入即可。
package com.example.j8;
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;
class Util {
// 构造函数私有
private Util() {
}
public static boolean exists(String str) {
return new File(str).exists();
}
/**
* 创建父目录
*
* @param str
*/
public static void createParentDirectory(String str) {
File file = new File(str);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
}
public static boolean copyFile(String str, String des) throws Exception {
boolean flag = false;
File file = new File(str);
File fileOut = new File(des);
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(file);
output = new FileOutputStream(fileOut);
copyFileHandler(input, output);
} catch (Exception e) {
flag = false;
} finally {
try {
input.close();
output.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
flag = true;
return flag;
}
private static void copyFileHandler(InputStream input, OutputStream output) throws Exception {
long start = System.currentTimeMillis();
byte data[] = new byte[2048];
int temp = 0;
while ((temp = input.read(data)) != -1) {
output.write(data, 0, temp);
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
public class MyCopy {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("格式错误,请使用如下格式:java copy 源文件地址 目的地址");
System.exit(1);
}
if (Util.exists(args[0])) {
Util.createParentDirectory(args[0]);
}
Util.copyFile(args[0], args[1]);
}
}