kotlin读取sd卡里的文件_如何在Kotlin中的Android中读写txt文件

I'm still pretty much a beginner in kotlin and android studio.

I can access most of the android widgets but I cannot access files and so far I managed to come across only the following code which does not work. The app crashes...

var recordsFile = File("/LET/Records.txt")

recordsFile.appendText("record goes here")

It will be much appreciated if I can also know how to create the file at a specific location. Like at root directory or internal storage or in a file in the internal storage.

Thanks..

解决方案

I just want to add on to TpoM6oH's answer. When working with Files, you may be not guaranteed with 100% success on the file operations you intend. So, it is a better practice to try and catch for exceptions like filenotfoundexception etc. and take a due care about the flow of program control.

To create a file at the external storage in Android, you can get the location using

Environment.getExternalStorageDirectory()

and check if the location exists. If it does not, create one and continue creating and writing your file using Kotlin

val sd_main = File(Environment.getExternalStorageDirectory()+"/yourlocation")

var success = true

if (!sd_main.exists())

success = sd_main.mkdir()

if (success) {

val sd = File("filename.txt")

if (!sd.exists())

success = sd.mkdir()

if (success) {

// directory exists or already created

val dest = File(sd, file_name)

try {

// response is the data written to file

PrintWriter(dest).use { out -> out.println(response) }

} catch (e: Exception) {

// handle the exception

}

}

} else {

// directory creation is not successful

}

Hope this helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值