【问题标题】:Cannot save to internal storage Android Studio无法保存到内部存储 Android Studio
【发布时间】: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


【解决方案1】:

我假设 “它提示我没有找到文件” 你的意思是来自 Logger 的 “不存在” 信息。 根据我检查您的saveFile() 方法是否正常工作并且文件已创建。 这个 !file.exists() 开头的 loadFile() 返回 true,因为内部文件的管理方式不同,因此文件不存在(它的路径与 "data.json" 不同)并且您的方法完成由于return 声明。

所以删除

if (!file.exists()) {
    d(TAG, "doesn't exist")
    return
}

阻塞,它应该可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    • 2013-10-28
    • 2023-03-10
    • 2015-09-07
    • 2014-09-08
    相关资源
    最近更新 更多