Search code examples
android-studiokotlinandroid-assetsreadlines

How to specify path to read a .txt file in assets directory


I want to get details about a selected harbour,by taking val s from a list extracted using readLines from a .txt file, where each harbour has a .txt file in the assets directory. I generate the file name but when the app is run in the emulator I get a file not found error. In this case I am trying to get at a file called 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,

The log cat reads :-

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)

The full windows path to the file is :- C:\Users.......\OneDrive\Coding projects\tide2a\app\src\main\assets\Brehatharm.txt

I am sure the file is there, and spelled correctly, so I suspect I am specifying the path incorrectly. Please advise me.


Solution

  • Files in assets/ cannot be accessed using the File class. Use context.assets to get the AssetManager, and you can open InputStreams to the files.