2つのフォルダパスを入力し、1つのフォルダ(コンテンツを含む)を別のフォルダにコピーします...
2801 ワード
学習の過程で自分で記録しておく
========================================Talk is cheap, show me the code=======================================
転載先:https://www.cnblogs.com/lcy0515/p/10807941.html
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test3 {
/*
* , ( )
*/
static BufferedReader br;
public static void main(String[] args) throws IOException {
File src = getDir(); //
File dest = getDir(); //
br.close();
if (src.equals(dest)) {
System.out.println(" !");
} else {
copyFile(src, dest);
}
}
public static File getDir() {
try {
// ,
br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(" ");
while (true) {
String line = br.readLine();
File dir = new File(line);
if (!dir.exists()) {
System.out.println(" ! :");
} else if (dir.isFile()) {
System.out.println(" , :");
} else {
return dir;
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
/**
* 1. void 2. File src, File dest
*
* @throws IOException
*/
public static void copyFile(File src, File dest) throws IOException {
File newDir = new File(dest, src.getName());
newDir.mkdirs();
File[] subFiles = src.listFiles(); //
for (File subFile : subFiles) {
if (subFile.isFile()) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(subFile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(new File(newDir, subFile.getName())));) {
int len;
while ((len = bis.read()) != -1) {
bos.write(len);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else { //
copyFile(subFile, newDir);
}
}
}
}
========================================Talk is cheap, show me the code=======================================
転載先:https://www.cnblogs.com/lcy0515/p/10807941.html