如何指定在资产目录中读取 .txt 文件的路径

问题描述

我想通过从使用 readLines 从 .txt 文件中提取的列表中获取 val 来获取有关选定港口的详细信息,其中每个港口在资产目录中都有一个 .txt 文件。我生成了文件名,但是当应用程序在模拟器中运行时,我收到一个找不到文件的错误。 在这种情况下,我试图获取一个名为 Brehatharm.txt 的文件

 var portChosen = "Brehat"
        //"tide2a/app/src/main/assets/"+//various paths to try 
fileName = "assets/"+portChosen+"harm.txt"
val harmConsList:List<String> = File(fileName).readLines()

        val portDisplayName = harmConsList[0]
        val longTude = harmConsList[1]
        val MTL =harmConsList[2]
etc,

日志猫读:-

2021-01-10 15:40:34.044 7108-7108/com.example.tide2a E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.tide2a,PID: 7108
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tide2a/com.example.tide2a.MainActivity}: java.io.FileNotFoundException: assets/Brehatharm.txt: open failed: ENOENT (No such file or directory)

文件的完整 Windows 路径是:- C:\Users.......\OneDrive\Coding projects\tide2a\app\src\main\assets\Brehatharm.txt

我确定文件在那里,并且拼写正确,所以我怀疑我指定的路径不正确。请指教。

解决方法

无法使用 File 类访问 assets/ 中的文件。使用 context.assets 获取 AssetManager,您可以打开 InputStreams 到文件。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...