18 Aug 2021

Read large file from the external storage in Android

 Hi All,


There are many features or snippet of code, which we are using in our daily development.
Here I am sharing some common basic function for make our life easy and fast in the development. Below is the code written in the Kotlin.

File path can be : 
val file = File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "test.txt")

  •  Read file from external storage:

fun readFileData(file: File): String
    {
        val sb = StringBuilder()

        if (file.exists()) {
            try {
                val bufferedReader = file.bufferedReader();
                bufferedReader.useLines { lines ->
                    lines.forEach {
                        sb.append(it)
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return sb.toString()
    }

  • Read file from assets:

fun loadJSONFromAsset(mContext: Context, fileName: String): String {
        val inputStream = mContext.assets.open(fileName)
        val size = inputStream.available()
        val buffer = ByteArray(size)
        inputStream.read(buffer)
        inputStream.close()
        return String(buffer, Charsets.UTF_8)
    }

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

No comments:

Post a Comment