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

如何在kotlin中读写android中的txt文件,android,kotlin,Android,Kotlin,在kotlin和android studio中,我基本上还是个初学者。 我可以访问大多数android小部件,但我无法访问文件,到目前为止,我只遇到了以下不起作用的代码。应用程序崩溃 var recordsFile = File("/LET/Records.txt") recordsFile.appendText("record goes here") 如果我也能知道如何在特定位置创建文件,我将不胜感激。例如在根目录或内部存储中,或在内部存储中的文件中。 谢谢..您需要为文件使用内部或外部存储

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

var recordsFile = File("/LET/Records.txt")
recordsFile.appendText("record goes here")
如果我也能知道如何在特定位置创建文件,我将不胜感激。例如在根目录或内部存储中,或在内部存储中的文件中。
谢谢..

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

内部:

val path = context.getFilesDir()
外部:

val path = context.getExternalFilesDir(null)
如果要使用外部存储,则需要向清单添加权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
然后创建您的文件:

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() }

我只想补充一下TpoM6oH的答案。在使用文件时,可能无法保证您的文件操作100%成功。因此,更好的做法是尝试捕获异常,如filenotfoundexception等,并适当注意程序控制流

要在中的外部存储器中创建文件,可以使用

Environment.getExternalStorageDirectory()
并检查该位置是否存在。如果没有,请创建一个,然后使用继续创建和写入文件


希望这有帮助。

Kotlin使文件读写变得非常简单

对于内部存储器的读/写:

context.openFileOutput(filename, Context.MODE_PRIVATE).use {
    it.write(message.toByteArray())
}
.
.
.
val file = File(context.filesDir, "myfile.txt")
val contents = file.readText() // Read file
val file = File(Environment.getExternalStorageDirectory()+"/path/to/myfile.txt")
file.writeText("This will be written to the file!")
.
.
.
val contents = file.readText() // Read file
对于读取/写入外部存储器:

context.openFileOutput(filename, Context.MODE_PRIVATE).use {
    it.write(message.toByteArray())
}
.
.
.
val file = File(context.filesDir, "myfile.txt")
val contents = file.readText() // Read file
val file = File(Environment.getExternalStorageDirectory()+"/path/to/myfile.txt")
file.writeText("This will be written to the file!")
.
.
.
val contents = file.readText() // Read file

共5行:将文件创建到内部目录(如果不存在),写入文件,读取文件

val file = File(ctx.filesDir, FILE_NAME)
file.createNewFile()
file.appendText("record goes here")
val readResult = FileInputStream(file).bufferedReader().use { it.readText() }
println("readResult=$readResult")
fun-loadWords(context:context):数组列表{
val Word=ArrayList()
变量行:字符串
var word=“”
变量权重=0
试一试{
val读取器:BufferedReader
val file=context.assets.open(“spam_keywords.txt”)
reader=BufferedReader(InputStreamReader(文件))
while((reader.readLine())!=null){
line=reader.readLine()
val st=StringTokenizer(行)
而(st.hasMoreElements()){
word=st.nextElement().toString()
}
添加(Word)
}
}捕获(e:例外){
e、 printStackTrace()
}
println(Word)
回信
}

我认为您必须在“/LET”可能还不存在的情况下调用其中的.mkdirs()。此外,对于写作,他可以只使用file.appendText(最终解析为类似于您所写的内容,只是appendText将字符集设置为UTF8)您是否使用
android.content.Context
?如果您在活动中,您可以调用
getFilesDir()
,否则,您将需要获取上下文对象。在一个片段中,您可以调用
getContext().getFilesDir()
。getExternalStorageDirectory().getPath()和使用文件(filePath/,即内部存储路径,“/LET/HelloWorld.txt”)分配的文件,但我无法对其进行写入。应用程序崩溃。我试过writeText和appendText。。。我找不到如何创建该文件。当我检查存储时,没有创建文件夹或文件,应用程序在这两个方面都崩溃了……没有任何文档可以解释为什么需要上下文,或者上下文应该来自哪里。是否存在我们应该访问(或不访问)内部存储的特定位置?似乎一个人应该能够在什么是
响应
时写入该目录?您正在写入文件的字符串?@BransonCamp是。响应是写入API级别29 java中不推荐使用的filegetExternalStorageDirectory的数据。在这里更新如何编写文件列表?我们可以将上面的代码放入for循环并执行到要写入的文件数吗?@MADLAD是的,您可以使用for循环迭代N个文件。非常感谢!最后,Kotlin给出了一个关于读取和写入.txt文件的重要答案。再次感谢:)
fun loadWords(context: Context): ArrayList<String> {
        
    val Word = ArrayList<String>()
        var line: String
        var word = ""
        var weight = 0
        try {
            val reader: BufferedReader
            val file = context.assets.open("spam_keywords.txt")
            reader = BufferedReader(InputStreamReader(file))
            while ((reader.readLine()) != null) {
                line = reader.readLine()
                val st = StringTokenizer(line)
                while (st.hasMoreElements()) {
                    word = st.nextElement().toString()
                }
                Word.add(word)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        println(Word)
        return Word 
    }