【发布时间】:2018-01-27 22:37:40
【问题描述】:
似乎我已经尝试了人们提出的所有建议。 YouTube 视频、stackoverflow 帖子,但我似乎无法使用这些方法保存文件。我运行保存方法没有错误,但是当我稍后尝试读取它时,它提示我找不到文件。模拟器和真机都出现问题。
代码:
fun loadFile() {
if (!file.exists()) {
d(TAG, "doesn't exist")
return
}
try {
val scanner = Scanner(openFileInput("data.json"))
d(TAG, scanner.nextLine())
dateList = gson.fromJson(scanner.nextLine(), FileList::class.java).list
scanner.close()
} catch (e: Exception) {
if (e !is NoSuchElementException) {
Toast.makeText(this, R.string.error_loading, Toast.LENGTH_LONG).show()
d(TAG, "Error loading file", e)
} else {
d(TAG, "empty file")
}
}
}
fun saveFile() {
val fileList = FileList(dateList)
val json = gson.toJson(fileList)
try {
d(TAG, json)
val output = openFileOutput("data.json", Context.MODE_PRIVATE)
output.write(json.toByteArray())
d(TAG, "wrote")
output.close()
} catch (e: Exception) {
Toast.makeText(this, R.string.error_saving, Toast.LENGTH_LONG).show()
d(TAG, "Error saving file", e)
}
}
Logcat:
01-27 17:26:29.828 5918-5918/me.elian.contactsaver D/ContactSaver: doesn't exist
01-27 17:26:36.616 5918-5918/me.elian.contactsaver D/ContactSaver: {"list":[{"year":2018,"month":1,"day":27}]}
01-27 17:26:36.617 5918-5918/me.elian.contactsaver D/ContactSaver: wrote
01-27 17:26:38.190 5918-5918/me.elian.contactsaver D/ContactSaver: {"list":[{"year":2018,"month":1,"day":27},{"year":2018,"month":1,"day":26}]}
01-27 17:26:38.190 5918-5918/me.elian.contactsaver D/ContactSaver: wrote
01-27 17:26:48.972 5955-5955/me.elian.contactsaver D/ContactSaver: doesn't exist
【问题讨论】:
-
d(TAG, "doesn't exist")。坏消息!什么不存在?你知道吗?更改为d(TAG, "doesn't exist: " + file.getAbsolutePath());。此外,您没有向我们展示您是如何设置file的。请告诉我们路径。
标签: android file android-studio kotlin save