如果我对递归函数有所帮助,则可以这样做。它将源目录中的所有文件复制到destinationDirectory。
例:
rfunction("D:/MyDirectory", "D:/MyDirectoryNew", "D:/MyDirectory");
public static void rfunction(String sourcePath, String destinationPath, String currentPath) {
File file = new File(currentPath);
FileInputStream fi = null;
FileOutputStream fo = null;
if (file.isDirectory()) {
String[] fileFolderNamesArray = file.list();
File folderDes = new File(destinationPath);
if (!folderDes.exists()) {
folderDes.mkdirs();
}
for (String fileFolderName : fileFolderNamesArray) {
rfunction(sourcePath, destinationPath + "/" + fileFolderName, currentPath + "/" + fileFolderName);
}
} else {
try {
File destinationFile = new File(destinationPath);
fi = new FileInputStream(file);
fo = new FileOutputStream(destinationPath);
byte[] buffer = new byte[1024];
int ind = 0;
while ((ind = fi.read(buffer))>0) {
fo.write(buffer, 0, ind);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (null != fi) {
try {
fi.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != fo) {
try {
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}