그놈의 안드로이드
SharedPreferences 외부 파일로 저장 / 불러오기 본문
저장
val preferences = getDefaultSharedPreferences(BaseApp.appContext)
val keys = preferences.all
val properties = Properties()
for ((key, value1) in keys) {
val value = value1.toString()
properties.setProperty(key, value)
}
try {
val root = Environment.getExternalStorageDirectory()
val dir = root.absolutePath.toString() + "/appname"
val fileDir = File(dir)
if (!fileDir.exists()){
fileDir.mkdir()
}
val path = root.absolutePath.toString() + "/appname/data.txt"
val file = File(path)
val fileOut = FileOutputStream(file)
properties.storeToXML(fileOut, "External Preferences")
fileOut.close()
} catch (e: Exception) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
불러오기
try {
val preferences = PreferenceManager.getDefaultSharedPreferences(BaseApp.appContext)
val root = Environment.getExternalStorageDirectory()
val dir = root.absolutePath.toString() + "/appname"
val fileDir = File(dir)
if (!fileDir.exists()){
return
}
val path = root.absolutePath.toString() + "/appname/data.txt"
val file = File(path)
val fileInput = FileInputStream(file)
val properties = Properties()
properties.loadFromXML(fileInput)
fileInput.close()
val enuKeys = properties.keys()
val editor = preferences.edit()
while (enuKeys.hasMoreElements()) {
val key = enuKeys.nextElement() as String
val value = properties.getProperty(key)
editor.putString(key, value)
editor.commit()
}
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
'안드로이드 > 안드로이드' 카테고리의 다른 글
안드로이드 GSON 라이브러리 (0) | 2020.03.29 |
---|