1. 程式人生 > >java 剪下資料夾下的所有檔案包括資料夾到另一個碟符並保留檔名

java 剪下資料夾下的所有檔案包括資料夾到另一個碟符並保留檔名

public class IORename {
//目標碟符
private static final char destPan= 'e';
public static void main(String[] args) {
File file = new File("d:/dd");
rename2Files(file);
}
// 剪下多層檔案
public static void rename2Files(File file) {
if (file.exists()) {
// 1.取出檔名然後修改碟符
String dest = file.getAbsolutePath();
StringBuilder builder = new StringBuilder(dest);
builder.setCharAt(0, destPan);
dest = builder.toString();
//目標檔案
File file2 = new File(dest);
if (file.isDirectory()) {
// 2.建立dest資料夾
file2.mkdirs();
File[] files = file.listFiles();
for (File f : files) {
rename2Files(f);
}
}
// 3.將檔案拷貝到另外碟符的同路徑同名檔案下
if (!file2.exists()) {
// 建立目標檔案
try {
file2.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// 4.剪下檔案
file.renameTo(file2);
// 5確保刪除資料夾
file.delete();
}
}


}