「Kotlin入門」write()でテキストファイルに書き込むサンプル

2021年3月31日

書式
public static Path write(Path path, Iterable<? extends CharSequence> lines,
Charset cs, OpenOption… options) throws IOException
使用例

import java.io.IOException
import java.nio.file.Files
import java.nio.charset.Charset
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
import java.util.Arrays
import java.util.ArrayList

fun main() {
    val flPath = Paths.get("C:\\data", "sample.txt")
    val cst = Charset.forName("UTF-8")
    val cftLst: List<String> = ArrayList(Arrays.asList("A001", "B002", "C003", "D004", "E005"))

    try {
        Files.write(
            flPath, cftLst, cst,
            StandardOpenOption.TRUNCATE_EXISTING
        )
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

 

Kotlin

Posted by arkgame