You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android设备文件重命名后丢失格式,如何正确实现文件重命名?

Android 文件重命名保留格式的解决方案

你的问题核心是新文件名没有带上原文件的扩展名,导致系统无法识别文件格式。下面是具体的修正方案:

1. 提取原文件的扩展名

先从原文件中获取它的扩展名(比如.pdf、.jpg这类后缀),可以用这个工具函数实现:

fun getFileExtension(file: File): String {
    val fileName = file.name
    val lastDotIndex = fileName.lastIndexOf(".")
    return if (lastDotIndex != -1 && lastDotIndex < fileName.length - 1) {
        fileName.substring(lastDotIndex + 1)
    } else {
        "" // 原文件无扩展名时返回空字符串
    }
}

2. 修正重命名逻辑

修改renameFile函数,把原文件的扩展名拼接到新文件名后,确保格式不丢失:

fun renameFile() {
    val originalFile = listDownloadsFile.get(i).file
    // 获取原文件扩展名
    val extension = getFileExtension(originalFile)
    // 拼接带扩展名的新文件名
    val newFileName = if (extension.isNotEmpty()) {
        "$new_name.$extension"
    } else {
        new_name // 原文件无扩展名则直接用新名称
    }
    val targetFile = File("/storage/emulated/0/Download/", newFileName)
    
    val isSuccess = originalFile.renameTo(targetFile)
    Log.d("kkdkdk", "重命名结果:$isSuccess")
}

3. 修复文件列表加载的错误

你的getAllFileInDownload函数存在变量名不一致的问题(listDownloadsFile和files),修正后如下:

private fun getAllFileInDownload() {
    val downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
    val listDownloadsFile = downloadDir.listFiles() ?: return // 判空避免空指针
    
    listDownloads.clear() // 先清空列表,避免重复添加
    listDownloadsFile.forEach { file ->
        listDownloads.add(FileData(file, false))
    }
}

4. 适配Android版本权限

  • Android 9及以下:需要在AndroidManifest.xml中声明权限,并且动态申请:
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
  • Android 10及以上:系统默认启用分区存储(Scoped Storage),直接用File类操作公共目录可能失败,建议改用**存储访问框架(SAF)**或MediaStore API完成重命名。如果必须用File,可以在AndroidManifest.xml的application标签中临时兼容:
    android:requestLegacyExternalStorage="true"
    
    注意:这个属性在Android 11及以上会被忽略,长期适配建议转向SAF。

内容的提问来源于stack exchange,提问作者Xuân Đức Nguyễn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 11:15:26