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?
CodePudding user response:
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