HanJo Jang
HanJo Jang

Reputation: 23

Reading JSON or text file in resource folder

I am developing Kotlin app. I am trying to read text and JSON files which I stored in resource folder(res/raw/file.txt). Looking at the hierachy of app structure, I put absolute path(../../res/raw/file.txt) for file reader.

Unfortunately, my app cannot find the file.

Can you tell me how I can read files stored in res/raw? If I store file in wrong directory, can you tell me where to store and how to access them?

Thanks

Upvotes: 1

Views: 4641

Answers (1)

mol
mol

Reputation: 2657

If you want to read a file from res/raw folder you can obtain InputStream by R.raw.yourfile id like this:

resources.openRawResource(R.raw.yourfile)

Or you can open file by Uri:

val uri = Uri.parse("android.resource://com.example.your_package/raw/yourfile")
val file = File(uri.getPath());

Alternatevily you can put your files in assets/ folder and get InputStream like this:

assets.open("yourfile.txt")

Upvotes: 8

Related Questions