Android OutOfMemoryException同时保存对文件的JSON响应以进行解析

时间:2014-09-27 15:11:24

标签: android json out-of-memory

我得到一个OutOfMemoryException试图简单地使用JSON将JSON响应解析为树结构,所以我切换到流式JSON解析方法。现在,当尝试将响应保存到文件时,我收到OutOfMemoryException。有什么想法吗?

  List<CurrencyPair> currencyPairs = new ArrayList<CurrencyPair>();
  URL url = new URL("http://pubapi.cryptsy.com/api.php?method=orderdatav2")

  File sdCard = Environment.getExternalStorageDirectory();
  File directory = new File(sdCard.getAbsolutePath() + "/zTrader");
  directory.mkdirs();
  File file = new File(directory, "cryptsy_response.json");

  BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
  BufferedWriter out = new BufferedWriter(new FileWriter(file));

  char[] cbuf = new char[255];
  while ((in.read(cbuf)) != -1) { // <-- CRASH HAPPENS HERE
    out.write(cbuf);
  }
  in.close();
  out.close();

  FileInputStream fis = new FileInputStream(file);
  InputStreamReader fileInputStreamReader = new InputStreamReader(fis);
  Reader bufferedReader = new BufferedReader(fileInputStreamReader);
  JsonReader reader = new JsonReader(bufferedReader);

  reader.beginObject();
  Map<CurrencyPair, Integer> newMap = new HashMap<CurrencyPair, Integer>();

  while (reader.hasNext()) {

    String name = reader.nextName();

    if (name.equals("success")) {
      reader.nextInt();
    }
    else if (name.equals("return")) {
      reader.beginObject();

      while (reader.hasNext()) {
        String pairString = reader.nextName();
        String[] currencies = pairString.split("/");
        CurrencyPair currencyPair = new CurrencyPair(currencies[0], currencies[1]);
        currencyPairs.add(currencyPair);

        reader.beginObject();
        while (reader.hasNext()) {
          if (reader.nextName().equals("marketid")) {
            Integer id = Integer.valueOf(reader.nextString());
            newMap.put(currencyPair, id);
          }
          else {
            reader.skipValue();
          }
          if (sleep)
            Thread.sleep(25);
        }
        reader.endObject();
        if (sleep)
          Thread.sleep(25);
      }
    }
  }
  reader.close();
  file.delete();

0 个答案:

没有答案