----------android培训、java培训、期待与您的交流----------
复制文件,仅仅是指定的某个文件,比较简单,但是某个文件夹,就有点技巧
public static void copyFolder(String oldPath, String newPath) {
try {
(new File(newPath)).mkdirs(); //确保新路径的文件夹存在
File a = new File(oldPath);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file[i]);
} else {
temp = new File(oldPath + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(newPath
+ "/" + (temp.getName()).toString());
byte[] b = new byte[1024];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.close();
input.close();
}
if (temp.isDirectory()) {//如果是子文件夹
copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
}
}
} catch (Exception e) {
System.out.println("复制文件夹出错" + e.getMessage());
}
}
测试
public static void main(String[] args) throws Exception {
copyFolder("C:\\1", "D:\\1");
}