如何在android中的kotlin读取和写入txt文件

我还是一个在kotlin和android studio的初学者。 我可以访问大多数的Android小部件,但我无法访问文件,到目前为止,我设法遇到只有下面的代码不起作用。 该应用程序崩溃…

var recordsFile = File("/LET/Records.txt") recordsFile.appendText("record goes here") 

如果我也可以知道如何在特定位置创建文件,将会非常感激。 就像在根目录或内部存储器或内部存储器中的文件一样。 谢谢..

我只是想补充一下TpoM6oH的回答。 使用“文件”时,可能无法保证100%的文件操作成功。 因此,尝试捕捉filenotfoundexception等exception是一个更好的做法,并应该注意程序控制的流程。

要在外部存储器上创建文件,可以使用该位置

 Environment.getExternalStorageDirectory() 

并检查该位置是否存在。 如果没有,请创建一个,然后使用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 { PrintWriter(dest).use { out -> out.println(response) } } catch (e: Exception) { // handle the exception } } else { // directory creation is not successful } } 

希望这可以帮助。

您需要为文件使用内部或外部存储目录。

内部:

 val path = context.getFilesDir() 

外部:

 val path = context.getExternalFilesDir(null) 

如果您想使用外部存储,则需要为清单添加权限:

  

创建你的目录:

 val letDirectory = File(path, "LET") letDirectory.mkdirs() 

然后创建你的文件:

 val file = File(letDirectory, "Records.txt") 

然后你可以写信给它:

 FileOutputStream(file).use { it.write("record goes here".getBytes()) } 

要不就

 file.appendText("record goes here") 

并阅读:

 val inputAsString = FileInputStream(file).bufferedReader().use { it.readText() } 

这是我的完整活动代码,适合我

 package com.coding180.project016 import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import java.io.BufferedReader import java.io.IOException import java.io .InputStreamReader import android.widget.Toast import android.app.Activity import java.io.OutputStreamWriter class MainActivity: AppCompatActivity () { override fun onCreate (savedInstanceState: Bundle?) { super.onCreate (savedInstanceState) setContentView (R.layout.activity_main) val et1 = findViewById (R.id.et1) as EditText if(fileList().contains("notes.txt")) { try { val file = InputStreamReader(openFileInput("notes.txt")) val br = BufferedReader(file) var line = br.readLine() val all = StringBuilder() while (line != null) { all.append(line + "\n") line = br.readLine() } br.close() file.close() et1.setText(all) } catch (e:IOException) { } } val button1 = findViewById (R.id.button1) as Button button1.setOnClickListener { try { val file = OutputStreamWriter(openFileOutput("notes.txt", Activity.MODE_PRIVATE)) file.write (et1.text.toString()) file.flush () file.close () } catch (e : IOException) { } Toast.makeText(this, "data were recorded", Toast.LENGTH_SHORT).show() finish () } } }