简体   繁体   English

递归目录遍历引起的堆栈溢出错误

[英]Stack Overflow error from recursive directory traversal

When I'm running this method I immediately get a stack overflow exception so obviously the method keeps recursively calling itself however I'm not sure why. 当我运行此方法时,我立即得到一个堆栈溢出异常,因此很明显,该方法会不断递归调用自身,但是我不确定为什么。 For reference the file structure I'm testing it with is a load of folders and in those folders are files, no other folders 作为参考,我正在测试的文件结构是文件夹的负载,在那些文件夹中是文件,没有其他文件夹

    public void files(File[] f)
    {
    if(f == null){
        return;
    }
    else
    {   
    for(int i = 0; i < f.length; i++)
    {
        if(f[i].isFile() && (f[i].getName().contains(".mp3") || f[i].getName().contains(".m4a"))) //iterate through files and check if each file matches the required criteria 
        {
                String fullname = f[i].getName();
                Log.v("full name", fullname);
                String name = null;
                if(fullname.contains(".mp3"))
                {
                name = fullname.substring(0, fullname.lastIndexOf(".mp3"));
                }
                else if(fullname.contains(".m4a"))                                  //Removing file extensions of music file so they can be displayed using an appropriate name
                {
                    name = fullname.substring(0, fullname.lastIndexOf(".m4a"));
                }
                list.add(name);
                mp3.add(f[i]);
                Log.v("added", name);
        }
        if(f[i].isDirectory())
        {
            File inner[] = files[i].listFiles();
            files(inner);
        }

    }
    }

   }

Maybe some of the files are "." 也许某些文件是“。” and ".." which means , i think, the current folder and back one folder. 和“ ..”,我想是指当前文件夹,然后返回一个文件夹。

So in your isDirectory() part of the if check also check if f[i]!="." 因此,在if的isDirectory()部分中,还要检查f [i]!=“。 and f[i]!=".." 和f [i]!=“ ..”

if(f[i].isDirectory() and f[i]!="." and f[i]!="..")
    {
        File inner[] = files[i].listFiles();
        files(inner);
    }

EDIT: 编辑:

As @Jon said, try to add more debug to it and see where it breaks exactly. 就像@Jon所说的那样,尝试向它添加更多调试信息,看看它到底在哪里中断。

LATER EDIT: 之后编辑:

For future readers, the problem was here: 对于将来的读者来说,问题出在这里:

    //File inner[] = files[i].listFiles();
    File inner[] = f[i].listFiles();

So super dumb mistake on my part, when copying the code from a previous non recursive implementation I forgot to change files to f in 因此,我非常愚蠢的错误是,从以前的非递归实现中复制代码时,我忘记将文件更改为f

if(f[i].isDirectory())
        {
            File inner[] = files[i].listFiles();
            files(inner);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM