11
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

kotlinでテキストファイルの読み込み、書き出し

Last updated at Posted at 2017-09-22

##前提

test.txt
1 2 3 4 5

このファイルへの読み込み書き出し

###読み込み
####Scannerでの読み込み

try{
    val file = File("パス")
    val scan = Scanner(file)
    var i = scan.nextLine()
    i = scan.next()
}catch (e: FileNotFoundException){
    println(e)
}

####FileReaderでの読み込み

try{
    val file = File("パス")
    val filereader = FileReader(file)
    var rd: Int = filereader.read()
    while (rd != -1) {
        print(rd.toChar())
        rd = filereader.read()
    }
}catch (e: FileNotFoundException){
    println(e)
}

###書き出し

    val fil = FileWriter("パス")
    val pw = PrintWriter(BufferedWriter(fil))
    pw.println("3")
    pw.println("5")
    pw.println("7")
    pw.close()

###出力後

test.txt
3
5
7

自分用のメモに

11
17
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?