StackoverflowException复制文件夹时发生

时间:2012-08-03 12:18:41

标签: android copy directory android-sdcard stack-overflow

当以下代码执行更多嵌套文件夹和文件时,它会给出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();
    }
}

请提供所需的增强功能。

谢谢

1 个答案:

答案 0 :(得分: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()的文件,您很可能会发现问题所在。