LoginSignup
1
1

More than 5 years have passed since last update.

Kotlinで内部ストレージに保存・読み取り

Posted at

保存するとき

val fileName = "FileName"
val content1 = "Content1"
val content2 = "Content2"

val fos: FileOutputStream = openFileOutput(fileName, Context.MODE_PRIVATE)

fos.write(content1\n.toByteArray())
fos.write(content2.toByteArray())
fos.close()

このときのFileNameの中身は下のようになる。

FileName
Content1
Content2

ここで、AndroidStudioにおけるエミュレータの内部データの見方
①Device File Explorer(画面右下)
②エミュレータを選ぶ
③data/data/ドメイン.プロジェクト名/filesの中にある!

読み取るとき


val fis: FileInputStream = openFileInput(fileName)
val isr: InputStreamReader = InputStreamReader(fis)
val reader: BufferedReader = BufferedReader(isr)

val contentA = reader.readLine()
// contentA -> Content1
val contentB = reader.readLine()
// contentB -> Content2
fis.close()

readLineと書くことによって、一行ずつ読むことができる。
その行に何もない場合はnullと出力される。

1
1
0

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
1
1