DEBUG模式下的递归函数导致文件夹复制错误

时间:2017-11-08 16:10:13

标签: android file debugging recursion copy

在Android !!! DEBUG模式下的递归功能导致文件夹复制错误

public class FileBox {
    public static boolean copySrc2Tar(File sourceLocation, File targetLocation) {

//        File sourceLocation = new File(src.getPath()); //ShallowCopy?
//        File targetLocation = new File(tar.getPath()); //DeepCopy?

        if (sourceLocation.isDirectory()) {
            if (!targetLocation.exists()) {
                targetLocation.mkdir();
            }

            String[] children = sourceLocation.list();
            for (int i = 0; i < sourceLocation.listFiles().length; i++) {

                copySrc2Tar(new File(sourceLocation, children[i]),
                        new File(targetLocation, children[i]));
            }
        } else {
            InputStream in = null;
            OutputStream out = null;
            try {

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

                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
                if(in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
            }
        }

        return true; 
    }
}




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.acty_mnhnflfldr);

    InputStream in = null;
    OutputStream out = null;
    File curPath;

    if(getExternalStorageState().equals(MEDIA_MOUNTED) || getExternalStorageState().equals(MEDIA_MOUNTED_READ_ONLY))
        curPath = Environment.getExternalStorageDirectory();
    else
        curPath = Environment.getRootDirectory();

    File ff = new File(curPath +File.separator +"AFolder");
    File tt = new File(curPath +File.separator +"ZFolder");

    FileBox.copySrc2Tar(ff, tt, true);
}

我的文件夹层次结构如下:

AFolder ={FolderB, textB0.txt, textB1.txt}

FolderB ={FolderC, textC0.txt}

然后运行上面的代码, 在Android Studio上正常模式下运行良好。 'AFolder'及其所有元素都复制到'ZFolder'中。结果是......

ZFolder ={FolderB, textB0.txt, textB1.txt}

FolderB ={FolderC, textC0.txt}

但是

在“DEBUG”模式下, 'ZFolder'没有被完美复制。总是一些元素 不见了。

我找不到。上面的代码有什么问题?

0 个答案:

没有答案