下载JSON文件并保存在内部存储中(Android / Kotlin)

时间:2019-07-24 14:36:44

标签: android json kotlin

我有一个简单的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())
}

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

1 个答案:

答案 0 :(得分:0)

使用首选项:

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", "");
}

希望有帮助。