android无法从大型json文件中读取所有数据

时间:2016-09-02 03:33:28

标签: android

我想读取包含大量数据的json文件

我的代码

public String loadJSONFromAsset() {
        f = new File(Environment.getExternalStorageDirectory().getPath() + "/Contact Backup/name.json");
        String json = null;
        try {
            InputStream is;
            is = new BufferedInputStream(new FileInputStream(f));
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    } 

在我的logcat中,它只显示了一半的json文件。

任何帮助?

2 个答案:

答案 0 :(得分:2)

不要逐字节读取,使用扫描仪类逐行读取。

示例

public String loadJSONFromAsset() {
   file = new File(Environment.getExternalStorageDirectory().getPath() + "/Contact Backup/name.json");
   final StringBuilder text = new StringBuilder();
   try {
         Scanner sc = new Scanner(file);
         while (sc.hasNextLine()) {
            text.append(sc.nextLine());
         }
        sc.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
   return text.toString();
}

答案 1 :(得分:0)

实际上Logcat会截断任何太长的消息。如果您想显示所有消息,可以使用以下功能:

final int chunkSize = 2048;
for (int i = 0; i < s.length(); i += chunkSize) {
    Log.d(TAG, s.substring(i, Math.min(s.length(), i + chunkSize)));
}

您可以使用上述功能检查您的代码是否正常。