文件存儲
默認存儲到/data/data/<package name>/files/ 目錄下
openFileOutput()
- 第一個參數(shù)是文件名,
- 第二個參數(shù)操作模式 默認MODE_PRIVATE长已,存在相同文件名旦万,覆蓋;MODE_APPEND在后面追加
// 寫
fun save(inputText: String) {
try {
val output = openFileOutput("data", Context.MODE_PRIVATE)
val writer = BufferedWriter(OutputStreamWriter(output))
writer.use {
it.write(inputText)
}
} catch (e: IOException) {
e.printStackTrace()
}
}
//讀
fun read(): String {
val content = StringBuilder()
try {
val input = openFileInput("data")
val reader = BufferedReader(InputStreamReader(input))
reader.use {
reader.forEachLine {
content.append(it)
}
}
} catch (e: IOException) {
e.printStackTrace()
}
return content.toString()
}
SharedPreferences 存儲
SharedPreferences 文件都是存放在/data/data/<packagename>/shared_prefs/ 目錄下的
- 調(diào)用SharedPreferences對象的edit()方法獲取一個 SharedPreferences.Editor對象。
- 向SharedPreferences.Editor對象中添加數(shù)據(jù)蚪黑,比如 putBoolean()、putString()
- 調(diào)用apply()方法將添加的數(shù)據(jù)提交,從而完成數(shù)據(jù)存儲操作已添。
- 讀取數(shù)據(jù) getString()、getInt()