以下递归函数我写了,如果它可以帮助任何人。它会将源目录中的所有文件复制到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();
}
}
}
}
}
因此,你有一个目录充满文件,你想只复制这些文件?在输入端没有递归 - 例如将所有从子目录复制到主目录中? – akarnokd 2009-07-18 12:07:38
是的,确切地说。我感兴趣的只是将这些文件复制或移动到另一个目录(尽管在我刚刚要求复制的文章中)。 – user42155 2009-07-18 12:17:45
来自未来的更新。 Java 7具有来自[Files](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html)类的功能来复制文件。这是另一篇文章关于它http://stackoverflow.com/questions/16433915/how-to-copy-file-from-one-location-to-another-location – KevinL 2013-10-07 13:19:56