[Android][Kotlin]从文件中读取数据

1.示例代码:

private fun load() {
   
        var fileInputStream = openFileInput("data")
        
        //把文件内容读取进缓冲读取器(use方法会自动对BufferedReader进行关闭)
        BufferedReader(InputStreamReader(fileInputStream)).use {
            var line: String
            while (true) {
            line = it.readLine() ?: break //当有内容时读取一行数据,否则退出循环
            println(line) //打印一行数据 } }
        }

        }
    }

2.注意事项:

kotlin读取文件有多种方法,但是读取本地/data/data/.../files里的文件,必须要用fileInputStream

要不会出现Permission Denie错误.

那么kotlin读取文件有什么方法呢?一种是上面的方法,其次

第一种:

fun main(args: Array<String>) { 
       val file = File("build.gradle") //新建文件读取build.gradle的内容 
       //把文件内容读取进缓冲读取器 
       val bufferedReader = BufferedReader(FileReader(file)) 
        var line: String while (true) {
       //当有内容时读取一行数据,否则退出循环 
       line = bufferedReader.readLine() ?: break 
       println(line) //打印一行数据 
      } 
     bufferedReader.close() //关闭缓冲读取器 
}

第二种:

fun main(args: Array<String>) {
    //最简单打印文件内容的方法,readLines()方法可读取文件内容
    File("build.gradle").readLines().forEach(::println)
}

 以上两种都会出现权限问题.

参考:https://stackoverflow.com/questions/2022256/permission-denied-file-created-in-files

Easiest way to open the file (and create it at the same time) would be to use the openFileOutput("file.txt", MODE_PRIVATE) method.

This ensures that the file is only readable by your application (the same as you've have at the moment), plus it returns you a FileOutputStream so you can start writing to it.

参考:https://www.jianshu.com/p/832b19b8a025

相关推荐