-1

I created assets folder in a project, put my text file there. But when i run my app, it crashes with error: "Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)" I tried different ways to definite var filename for example: "assets/file.txt", "assets\file.txt", "./file.txt", but i still get the same error

package com.soft23.testfile

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.Text
import java.io.File

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        var str = "str"
        var filename = "file.txt"
        File(filename).forEachLine { str = it }
        setContent {
            Text(text = str)
        }
    }
}

Similar code in IntelliJ IDEA works fine What i did wrong?

  • `> Similar code in IntelliJ IDEA works fine`. It's not the same environment. In addition to @LemonTea's comment please check also this. https://stackoverflow.com/questions/12421814/how-can-i-read-a-text-file-in-android – ocos Sep 16 '22 at 10:18

1 Answers1

0

you can get asset file in Kotlin through this way:

    var reader:BufferedReader? = null
    try {
        //here i'm calling in Fragment, change activity?.getAssets()? = getAssets() if you calling in Activity
        reader = BufferedReader(InputStreamReader(activity?.getAssets()?.open("test.txt")));

        val returnString = StringBuilder()
         while (true) {
             val mLine = reader.readLine()
             if (mLine == null) break
             returnString.append(mLine + "\n")
        }
        
        //here is result
        Log.d("test.txt", "string = $returnString")
    } catch (e: Exception) {
        //log the exception
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (e: Exception) {
                //log the exception
            }
        }
    }

make sure your .txt file into this path:

project/app/src/main/assets

ninhnau19
  • 695
  • 1
  • 3
  • 16