简体   繁体   中英

How to Write/ Edit a txt file using Kotlin in Android Studio?

I am in the beginning of Android App learning phase. I have a .txt file in my assets folder consisting of strings in each line, like this-

AWOL    JJ  AWOL
Aaronic JJ  Aaronic
Aaronical   JJ  Aaronical

What I want to do is just replace JJ with NN and keep rest the same. My questions are-

  1. Is there a way to edit the already existing file, because all the solutions I found are talking about creating some other file using function File(<filename>) ?
  2. If I follow the solutions described on different websites, I can not access the file USING File() , it shows the error that the file can not be found even though I have created an empty file with the same name. I can not access the file if it is inside assets folder or inside app/src . So, instead I am using Context.assets.open(<filename>) for readin the orginal file which opens the file as inputstream . Although I don't know any other way of opening the file using File() for writing.
// FOR READING FROM ORIGINAL FILE
var inputStreamLemmDict = BufferedReader(InputStreamReader(context!!.assets.open("my_file.dict"))).readLines()

// FOR WRITING TO ANOTHER FILE
File("path_to/my_file.txt").bufferedWriter().use { out ->
        inputStreamLemmDict.forEach {
            var eachLineSplit = it.split("\\s".toRegex())
            if (eachLineSplit[1] == "NNN") {
                out.write("${eachLineSplit[0]}\tNN\t${eachLineSplit[2]}\n")
            }
            else {
            out.write("${it}\n")
            }
        }

Any help is appreciated. Thank you!

Hi you can use the following solution to achieve your desired result.

UPDATE : Please try this solution to read file from assets and get your result. This solution is not tested.

Make sure yourfilename.txt is under assets folder.

try {
val inputStream:InputStream = assets.open("yourfilename.txt")
      val text = inputStream.bufferedReader().use{it.readText()}

        println(text)
        text = text.replace("JJ".toRegex(), "NN")
        f.writeText(text)
}catch (e:Exception){
        Log.d(TAG, e.toString())
    }
fun main(args: Array<String>) {
var lineNumber = 0
var newString = ""
File("src/dataFile").forEachLine {
    ++lineNumber
    println("$lineNumber: $it")
    newString = it.replace("JJ", "NN")
    println("New string : $newString")
}
File("src/dataFile").writeText(newString) 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM