【问题标题】:Download JSON File and save in internal storage (Android/Kotlin)下载 JSON 文件并保存在内部存储中 (Android/Kotlin)
【发布时间】:2019-07-24 14:36:44
【问题描述】:

我有一个简单的 JSON 文件,我想下载该文件并将其保存在 内部 存储中。我的函数可以下载文件,但我无法将其保存在内部存储中:

val request = DownloadManager.Request(Uri.parse("Some_URL"))
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
        request.setTitle("Download")
        request.setDescription("File is downloading...")
        request.allowScanningByMediaScanner()
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "FILE_NAME")

        val manager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        manager.enqueue(request)

我在下载后尝试复制文件并将其保存在内部存储中:

val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
            "FILE_NAME")

val result = file.readText()
this.openFileOutput("FILE_NAME", Context.MODE_PRIVATE).use {
            it.write(result.toByteArray())
}

它有效,但我不喜欢它。我的做法,真的很糟糕。

【问题讨论】:

    标签: android json kotlin


    【解决方案1】:

    使用偏好:

    private void saveJson(Context context, String json) {
        final SharedPreferences sharedPreferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("json", json).apply();
    }
    
    private String loadJson(Context context){
        final SharedPreferences sharedPreferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
        return sharedPreferences.getString("json", "");
    }
    

    希望对你有帮助。

    【讨论】:

    • 那么,我通过 DownloadManager 下载文件并将该文件的内容保存在首选项中?
    • @jamesxbrown 是的,这是最简单的方法,应该足够了。使用您的解决方案,您必须处理许多边缘情况。其他应用程序也无法访问您的私有应用程序共享首选项。仅在他们已经扎根手机的情况下。
    • 对不起,我有点困惑。当我使用 DownloadManager 时,文件已经保存在外部存储中,不是吗?因此,当我将文件内容复制到首选项中或作为新文件时,这没有区别。还是我理解有误?
    • 读取您的文件,在您的应用偏好中保存 json 字符串,删除下载的文件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 2017-12-05
    • 2021-06-12
    相关资源
    最近更新 更多