【发布时间】:2015-02-15 05:24:58
【问题描述】:
我创建了一个复制类,它包含源文件夹和目标文件夹以及一组文件名。因此,此类搜索源文件夹,如果遇到与数组元素同名的文件,则将该文件复制到与源文件夹相同的文件夹结构中。 这是课程:
public class Copy {
File src, dest;
ArrayList array;
public Copy(File source, File destination ,ArrayList array) throws IOException{
this.src = source;
this.dest = destination;
this.array = array;
if(source.isDirectory()){
//list all the directory contents
String files[] = source.list();
for (String element : files){ //Serch in all the files and if it match with a selected format, copies it directory
if(array.contains(element)){
destination.mkdir();
}
};
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(source, file);
File destFile = new File(destination, file);
//recursive copy
new Copy(source,destination, array);
}
}
else{
//dest.mkdir();
if(array.contains(source.getName())){
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + source + " to " + destination);
}
}
}
}
这个类的问题是它只复制位于第一个或第二个内部文件夹中的文件。 例如,它可以成功复制这样的结构:
- Main Folder
-Inner Folder1
-File.pdf
-Inner Folder2
但它不能复制这样的结构:
- Main Folder
-Inner Folder1
-Inner Inner Folder1
-File.pdf
-Inner Folder2
因此,如果文件位于多个内部文件夹中,则会出现错误:
线程“AWT-EventQueue-0”中的异常 java.lang.StackOverflowError
指向这一行:`new CopyFiles(src,dest, array);
有解决办法吗?
【问题讨论】:
-
尝试将你的逻辑移到构造函数之外。
-
@ElliottFrisch 您的意思是将其转换为方法而不是类吗?
-
我的意思是递归地创建对象实例只会为垃圾收集器工作,它会使调试更加困难;在您的情况下,一个(或两个)静态方法似乎更有意义(至少对我而言)。