import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.RuntimeException;
public class Copy {
private static void copyFile(File from, File to) {
System.out.println("开始拷贝文件:" + from.getAbsolutePath() + " --------> " + to.getAbsolutePath());
byte buf[] = new byte[1024];
int count = 0;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(from));
bos = new BufferedOutputStream(new FileOutputStream(to));
if (bis != null && bos != null) {
while ((count = bis.read(buf)) != -1) {
bos.write(buf, 0, count);
bos.flush();
}
}
} catch (IOException e) {
throw new RuntimeException("文件复制异常!", e);
} finally {
try {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
} catch (IOException ex) {
throw new RuntimeException("文件关闭失败!", ex);
}
}
}
private static void copyDir(File fromDir, File toDir) {
if (!toDir.exists()) {
toDir.mkdirs();
}
File[] files = fromDir.listFiles();
for (File f : files) {
if (f.isFile()) {
File t = new File(toDir, f.getName());
if (confirmRewrite(t)) {
copyFile(f, t);
} else {
continue;
}
} else if (f.isDirectory()) {
if (f.getName().equals(toDir.getName())) {
continue;
}
copyDir(f, new File(toDir, f.getName()));
}
}
}
private static boolean confirmRewrite(File to) {
if (to.exists()) {
System.out.print("文件已经存在,是否覆盖?[y|n]:");
char confirm;
try {
confirm = (char) System.in.read();
System.in.skip(System.in.available());
} catch (IOException e) {
throw new RuntimeException(e);
}
if (confirm == 'y')
return true;
else
return false;
} else {
return true;
}
}
public static void main(String args[]) {
if (args.length != 2) {
System.err.println("Arguments num error!");
System.err.println("usage:java Copy " + "from to");
return;
}
File from = new File(args[0]);
File to = new File(args[1]);
if (!from.exists())
throw new RuntimeException(new FileNotFoundException("文件或目录不存在!"));
/*
* 目的地存在的话,如果是文件,则源地址也必须是文件;如果目的地是目录,源地址可以是文件,也可以是目录。
*/
if (to.exists()) {
// 如果目的地址存在
if (to.isFile() && from.isFile()) {
if(confirmRewrite(to)){
copyFile(from, to);
}else{
return;
}
} else if (to.isDirectory()) {
if (from.isFile()) {
File temp=new File(to, from.getName());
if(confirmRewrite(temp))
copyFile(from, temp);
} else {
copyDir(from, to);
}
} else {
throw new RuntimeException(new IOException("不允许将目录复制到文件!"));
}
} else {
// 如果目的地址不存在
if (from.isFile()) {
copyFile(from, to);
} else {
to.mkdirs();
copyDir(from, to);
}
}
}
}
转载于:https://my.oschina.net/sskxyz/blog/518815