1

当以下代码使用更多数量的嵌套文件夹和文件执行时,它会给出 StackOverflowException 请建议我避免它的方法。

 public void copyDirectory(File sourceLocation , File targetLocation){
    try {
        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists() && !targetLocation.mkdirs()) {
                throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath());
            }

            String[] children = sourceLocation.list();
            String s;
            if (children != null && children.length > 0) {
                for (int i = 0; i < children.length; i++) {
                    s = children[i];
                    copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
                }
            }

        } else {

            // make sure the directory we plan to store the recording in exists
            File directory = targetLocation.getParentFile();
            if (directory != null && !directory.exists() && !directory.mkdirs()) {
                throw new IOException("Cannot create dir " + directory.getAbsolutePath());
            }

            InputStream in = new FileInputStream(sourceLocation);
            OutputStream out = new FileOutputStream(targetLocation);

            // Copy the bits from instream to outstream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        addError(e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        addError(e.getMessage());
        e.printStackTrace();
    }
}

请建议所需的增强功能。

谢谢你

4

1 回答 1

0
if (children != null && children.length > 0) {
    for (int i = 0; i < children.length; i++) {
        s = children[i];
        copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
    }
}

在你的copyDirectory(),你递归地调用它。我认为某些文件会一遍又一遍地出现在方法中,而您通过一遍又一遍地调用New File()该对象来填充堆栈。

打印出您要发送到哪个文件copyDirectory(),您很可能会找出问题所在。

于 2012-08-03T12:23:45.793 回答