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

Flutter中如何将应用外部的文件数据赋值给变量

读取应用外部文件并赋值给变量实现方案

1. 前置权限配置(针对安卓平台)

  • 首先在AndroidManifest.xml中声明对应权限:
<!-- 安卓6.0-12版本所需的外部存储读权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- 安卓13及以上版本读取不同类型媒体文件需单独声明权限 -->
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
  • 安卓6.0及以上版本需要先动态申请存储权限,用户授权通过后再执行文件读取操作,避免权限不足导致崩溃。

2. 核心读取代码示例

2.1 读取文本类文件

Java版本

// 传入外部文件的完整路径,例:/storage/emulated/0/Download/test.txt
public String readExternalTextFile(String filePath) {
    StringBuilder contentBuilder = new StringBuilder();
    try {
        File targetFile = new File(filePath);
        FileInputStream fis = new FileInputStream(targetFile);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            contentBuilder.append(line).append("\n");
        }
        bufferedReader.close();
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // 返回值可直接赋值给字符串变量使用
    return contentBuilder.toString();
}

Kotlin版本

fun readExternalTextFile(filePath: String): String {
    return runCatching {
        File(filePath).readText()
    }.getOrElse {
        it.printStackTrace()
        ""
    }
}

2.2 读取二进制类文件(图片、音视频、压缩包等)

Java版本

public byte[] readExternalBinaryFile(String filePath) {
    byte[] fileContent = null;
    try {
        File targetFile = new File(filePath);
        FileInputStream fis = new FileInputStream(targetFile);
        fileContent = new byte[fis.available()];
        fis.read(fileContent);
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // 返回值可直接赋值给字节数组变量使用
    return fileContent;
}

Kotlin版本

fun readExternalBinaryFile(filePath: String): ByteArray? {
    return runCatching {
        File(filePath).readBytes()
    }.getOrElse {
        it.printStackTrace()
        null
    }
}

3. 注意事项

  • 不要硬编码外部存储路径,建议通过系统提供的公共目录API(如Environment.getExternalStorageDirectory()、Environment.getExternalStoragePublicDirectory())获取标准路径,避免不同厂商设备路径适配问题。
  • 安卓10及以上默认开启分区存储,若无需上架Google Play可在AndroidManifest.xml的application节点添加android:requestLegacyExternalStorage="true"临时兼容旧存储权限逻辑。
  • 读取超过100M的大文件时不要一次性加载到内存,建议分片读取处理,避免触发OOM异常。

内容的提问来源于stack exchange,提问作者blackdemon7

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:09:05