文件遍历异常Caused by: java.lang.StackOverflowError: stack size 1039KB

48 篇文章 2 订阅
4 篇文章 0 订阅

解决办法

  1. 采用广度优先遍历

原因

最早用的深度优先遍历,递归操作。没想到居然有用户 目录套目录,套了 6562 层(你是测试派来的吗。。。。)

更改

    private fun traverseFile(rootFile: File)  {
        var checkFile: File? = rootFile
        val queue = ArrayDeque<File?>()
        queue.offer(checkFile)

        while (!queue.isEmpty()) {
            checkFile = queue.poll()
            if (checkFile != null) {
                val files = checkFile.listFiles()
                if (files?.isNotEmpty() == true) {
                    for (file in files) {
                        if (file != null) {
                            if (file.isDirectory) {
                                queue.offer(file) //是文件夹入queue作为新的需要检索文件夹的路径
                            } else {
                                handleFile(file)
                            }
                        }
                    }
                }
            }
        }

    }

之前

    private fun traverseFile(file: File)  {
        if (isCancelled) {
            Log.i(TAG_DOCUMENT, "Cancel tas, user find file")
        } else if (file == null || !file.exists()) {
            Log.e(TAG_DOCUMENT, "file is null or not exist")
        } else if (file.isDirectory) {
            val childList: Array<File>? = file.listFiles()
            childList?.forEach {
                traverseFile(it)
            }
        } else {
            handleFile(file, result)
        }
    }

顺便说下,遍历遇到路径乱码的问题

  • Android文件路径获取是通过JNI调用
  • Android JNI用的字符串,是UTF-8的变更版本,即有部分字符不支持
  • 如果文件path有不支持的字符,就会崩溃。
  • (当然是测试故意创建的,一般用户,应该不会有这种情况)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值