skip to Main Content

I am using Microsoft operating system. Below are my code.
This one is written in android studio. Here I use ${project_name}appsrcmainres as the
resources root directory. I use the same package for the two classes declared below.

import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Paths

class Parser(fileName:String){
     val fileName=fileName
     val fileContent=getContent()

fun getContent():String{
    val encoded= Files.readAllBytes(Paths.get(".",fileName))
    //here relative path is the `res` folder in android studio 
    return String(encoded, Charset.defaultCharset())
    }
}

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val parser=Parser("default.vert")
    findViewById<TextView>(R.id.tv_test).also {
        it.text=parser.fileContent
        }
    }
}

it says:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.MainActivity}: java.nio.file.NoSuchFileException: ./default.vert

But in intellij idea community edition:

Basically the same code is used but with slightly different file path, because I mark one of
the folders to become the default resources root directory:

import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Paths

class Parser(fileName:String){
    val fileName=fileName
    val fileContent=getContent()
    fun getContent():String{
        val encoded= 
        Files.readAllBytes(Paths.get(".","src","main","resources",fileName))
        //here I used the most top level directory (maybe the scientific term is `root` 
        //but I am not sure)in the project which was named `Test`.
        return String(encoded, Charset.defaultCharset())
        }
    }

fun main(){
    val parser=Parser("test.vert")
    print(parser.fileContent)
}

and it prints the content:

layout (location=0) in vec4 vPosition;

void main(){
    gl_Position=vPosition;
}

How can I make the code run in Android studio too ? using kotlin

I have tried absolute path as well such as:
c:\users\${user_name}\..until_the_file\default.vert
but still got exception fileNotFoundException from android studio.

2

Answers


  1. Chosen as BEST ANSWER
    import android.content.Context
    
    class Program(val context: Context, val id:Int){
        val fileContent=getContent()
    
        private fun getContent(): String {
            try {
                val input = context.resources.openRawResource(id)
                val size=input.available()
                val buffer=ByteArray(size)
                input.read(buffer)
                input.close()
                return String(buffer,Charsets.UTF_8)
            }
            catch(e:Exception){
                e.printStackTrace()
                return ""
            } 
        }
    }
    

    Thanks to this https://www.geeksforgeeks.org/how-to-read-a-text-file-in-android/ it taught me how to use InputStream to read a file.

    I thought I will need to cast InputStream to FileInputStream because it is abstract class. In C++, we never can use abstract class unless we inherit from that abstact class an overriding the appropriate function.

    But this time in java/kotlin, we can do it straight away.


  2. Android handles files differently from a desktop JVM app. You must package the files in either your resources (appsrcmainresraw) or assets (appsrcmainassets), and then retrieve them either through resources.openRawResource() or assets.open() respectively. You will not be using direct file paths. Your local directories are not part of the packaged app installed on the device or emulator. You can only get InputStreams.

    Documentation: Resources and Assets

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search