【问题标题】:retrieving JSONObject from a file从文件中检索 JSONObject
【发布时间】:2013-05-05 00:40:33
【问题描述】:

我想将JSONObject 存储在一个文件中。 为此,我将对象转换为字符串,然后将其存储在文件中。 我使用的代码是:

String card_string =  card_object.toString();
//card_object is the JSONObject that I want to store.

f = new File("/sdcard/myfolder/card3.Xcard");
//file 'f' is the file to which I want to store it.

FileWriter  fw = new FileWriter(f);
fw.write(card_string);
fw.close();

代码按我的意愿工作。现在我想从文件中检索该对象。 我该怎么做?我对使用什么来读取文件感到困惑? InputStreamFileReaderBufferedReader 或什么。我是 JAVA / android 开发新手。

请帮忙。欢迎使用简单的语言详细解释在不同场景(如此类)中使用哪些 I/O 功能。我查看了文档,但欢迎您提出建议。

【问题讨论】:

标签: android json file-io


【解决方案1】:

您可以使用此代码读取文件。

BufferedReader input = null;
try {
    input = new BufferedReader(new InputStreamReader(
            openFileInput("jsonfile")));
    String line;
    StringBuffer content = new StringBuffer();
    char[] buffer = new char[1024];
    int num;
    while ((num = input.read(buffer)) > 0) {
        content.append(buffer, 0, num);
    }
        JSONObject jsonObject = new JSONObject(content.toString());

}catch (IOException e) {...}

然后你就可以使用你的jsonObject了:

从 JSON 对象中获取特定字符串

String name = jsonObject.getString("name"); 

获取特定的int

int id = jsonObject.getInt("id"); 

获取特定数组

JSONArray jArray = jsonObject.getJSONArray("listMessages"); 

从数组中获取项目

JSONObject msg = jArray.getJSONObject(1);
int id_message = msg.getInt("id_message");

【讨论】:

【解决方案2】:

使用可以使用BufferedReaderFileReader

File file = new File("/sdcard/myfolder/card3.Xcard");
StringBuilder text = new StringBuilder();
BufferedReader br = null;

try {
    br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
} catch (IOException e) {
    // do exception handling
} finally {
    try { br.close(); } catch (Exception e) { }
}

此外,我建议您使用Environment.getExternalStorageDirectory(); 来构建路径。这不是设备特定的。

干杯!

【讨论】:

【解决方案3】:
File contentfile = new File(filePath);
@SuppressWarnings("resource")
FileInputStream readJsonTextfile = new FileInputStream(contentfile);

Reader ContetnUrlJson = new InputStreamReader(readJsonTextfile);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
  • 2014-10-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多