File.list()闪退

在某一个目录中执行file.list,出现了闪退相关日志如下

java.io.UnixFileSystem.list(UnixFileSystem.java:346)
java.io.File.list(File.java:1131)
java.io.File.listFiles(File.java:1295)
-----
其他的日志
abort message:  JNI DETECTED ERROR IN APPLICATION: input is not valid Modified UTF-8: illegal continuation byte 0
string: '导入?'
input: '0xe5 0xaf 0xbc 0xe5 0x85 0xa5 0xe6 0xb5'
in call to NewStringUTF
from java.lang.String[] java.io.UnixFileSystem.list0(java.io.File)

大概就是出现了一个非法的编码文件名
然后在adb -shell -ls如下

Ahwad2024.xml             abc.kml                     yy.txt
Ahwad2024.xml.sjwb        area1                       zzrl-231122.apk
Ahwad2024cut.xml          ashp20240507                    zzrl-231123.apk
Ahwad2024cut.xml.sjwb         backups                     交点法17.road
Alarms                baxi.dwg                    导入\346\265

确实存在,在文件管理器中,找到它并删除
无法直接删除ls -ln

drwxrwx--x  5 0 1015      3488 2024-06-24 11:19 导入\346\265

问了ai,不断尝试解决方案如下

 

import android.content.Context
import android.net.Uri
import android.provider.DocumentsContract
import android.util.Log
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.StandardCopyOption

private const val TAG = "FileOperation"

class MyFile {




    /**
     * 使用 Java NIO 删除含有非 ASCII 字符的文件
     */
    fun deleteNIOFile(filePath: String) {
        val path = Paths.get(filePath)
        try {
            Files.delete(path)
        } catch (e: IOException) {
            Log.e("FileOperation", "Failed to delete file: $filePath", e)
        }
    }

    /**
     * 使用 Java NIO 删除含有非 ASCII 字符的文件
     * @param directoryPath 要删除文件所在的目录路径
     * @param fileName 要删除的文件名,可能包含非 ASCII 字符
     */
    fun deleteNIOFile(directoryPath: String, fileName: String) {
        val filePath = "$directoryPath$fileName"
        val path = Paths.get(filePath)
     try {
            Files.delete(path)
        } catch (e: IOException) {
            Log.e("FileOperation", "Failed to delete file: $filePath", e)
        }
    }

    /**
     * 使用 SAF (Storage Access Framework) 重命名含有非 ASCII 字符的文件
     */
    fun renameSAFFile(context: Context, fileUri: Uri, newName: String) {
        try {
            val updatedUri =
                DocumentsContract.renameDocument(context.contentResolver, fileUri, newName)
            Log.d("FileOperation", "File renamed: $updatedUri")
        } catch (e: Exception) {
            Log.e("FileOperation", "Failed to rename file: $fileUri", e)
        }
    }

    /**
     * 使用 Java NIO 重命名含有非 ASCII 字符的文件
     */
    fun renameNIOFile(sourcePath: String, targetPath: String) {
        val source = Paths.get(sourcePath)
        val target = Paths.get(targetPath)
        try {
            Files.move(source, target, StandardCopyOption.REPLACE_EXISTING)
        } catch (e: IOException) {
         Log.e("FileOperation", "Failed to rename file: $sourcePath to $targetPath", e)
        }
    }

    fun deleteNonAsciiFiles(directoryPath: String) {
        Log.d(TAG, "deleteNonAsciiFiles: ")
        val directory = Paths.get(directoryPath)
        try {
            Files.list(directory)
//                .filter { Files.isRegularFile(it) }
//                .filter { containsNonAsciiChars(it.fileName.toString()) }
                .filter{
                    it.fileName.toString().contains("导入")
                }
                .forEach {
                    Log.d("FileOperation", "deleteNonAsciiFiles: ${it.fileName}")
//                    deleteFile(it)
                    deleteDirectoryRecursively(it)
                    //deleteNIOFile(it.fileName.toString())

                }
        } catch (e: IOException) {
            Log.e(TAG, "deleteNonAsciiFiles: ",e)
            println("Error occurred while deleting non-ASCII files: $e")
        }
        Log.d(TAG, "deleteNonAsciiFiles: --")
    }


    fun deleteFile(filePath: Path) {
        if (Files.exists(filePath)) {
            try {
                Files.delete(filePath)
                println("File deleted: $filePath")
            } catch (e: IOException) {
                println("Failed to delete file: $filePath")
                e.printStackTrace()
            }
        } else {
            println("File not found: $filePath")
        }

        try {
            Files.delete(filePath)
        } catch (e: Exception) {
            Log.e(TAG, "deleteFile: ",e )
        }
    }

    fun deleteNonAsciiDirectory(directoryPath: String) {
        val path = Paths.get(directoryPath)
        try {
            deleteDirectoryRecursively(path)
        } catch (e: IOException) {
            println("Error occurred while deleting directory: $directoryPath")
            e.printStackTrace()
        }
    }

    private fun deleteDirectoryRecursively(path: Path) {
        Files.walk(path)
            .sorted(Comparator.reverseOrder())
            .forEach { file ->
                Log.d(TAG, "deleteDirectoryRecursively: ${file.fileName}")
                try {
                    Files.delete(file)
                    println("Deleted: $file")
                } catch (e: IOException) {
                    println("Failed to delete: $file")
                    e.printStackTrace()
                }
            }
    }



    fun containsNonAsciiChars(filename: String): Boolean {
        return filename.toByteArray().any { it.toInt() > 127 }
    }
}

调用方法

    private void toDelete(){
        try {
            final MyFile myFile = new MyFile();
//            myFile.deleteNIOFile("/storage/emulated/0/","导入\346\265");
            myFile.deleteNonAsciiFiles("/storage/emulated/0/");
        } catch (Exception e) {
            Log.e(TAG, "toDelete: ",new Exception() );
        }
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容