[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

 

写入数据参见另一篇博文:http://jameskaron.iteye.com/admin/blogs/2423085

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值