将json文件保存在缓存错误中

时间:2017-01-12 10:47:53

标签: android json gson

我需要你下载大约30 MB的Json并保存它以下载百分比。所以我已经实现了这段代码:

 private void downloadAirports()
{
    final OkHttpClient mOkHttpClient = new OkHttpClient();

    final Request mRequest = new Request.Builder().url(SERVICE_ENDPOINT).build();

    Observable.create(new Observable.OnSubscribe<String>()
    {
        @Override
        public void call(Subscriber<? super String> subscriber)
        {
            try {
                InputStream inputStream;
                Response response = mOkHttpClient.newCall(mRequest).execute();
                if (response.isSuccessful())
                {
                   inputStream = response.body().byteStream();
                   long len = response.body().contentLength();

                    Log.d("str",String.valueOf(len));

                    String progress = "0";
                    subscriber.onNext(progress);

                    final int bufferSize = 1024;
                    flag = false;
                    final byte[] buffer = new byte[bufferSize];
                    final StringBuilder out = new StringBuilder();
                    Reader in = new InputStreamReader(inputStream, "UTF-8");
                    ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();

                    long total = 0;
                    airp = new ArrayList<AirportObject>();
                    int count =0;

                    /*while ((count = inputStream.read(data)) != -1)
                    {
                        total += count;
                        progress = String.valueOf(total * 100 / len);
                        subscriber.onNext(progress);
                    }*/




                while(!flag)
                    {
                        count = inputStream.read(buffer);

                        if (count == -1)
                        {
                            progress = "100";
                            subscriber.onNext(progress);
                            flag = true;

                        }
                        else
                        {
                            byteOutStream.write(buffer);
                            total += count;
                            progress = String.valueOf(total * 100 / len);
                            subscriber.onNext(progress);
                        }
                    }



    //                        byte[] res = byteOutStream.toByteArray();

                    File jsonFile = new File(getActivity().getCacheDir(), FILE_NAME);
                    FileOutputStream outStream = new FileOutputStream(jsonFile);
                    byteOutStream.writeTo(outStream);

                    byteOutStream.flush();
                    inputStream.close();
                    byteOutStream.close();
                    Log.d("length", String.valueOf(jsonFile.length()));
                    Log.d("str",String.valueOf(len));

                    //write the whole data into the file
                   /* for(int i = 0; i < res.length; i++)
                    {
                        outStream.write(res[i]);
                    }*/

                    Gson gson = new Gson();

                    JsonReader reader = new JsonReader(new FileReader(jsonFile));

                    airp = new ArrayList<>();

                    reader.beginArray();


                    while (reader.hasNext())
                    {

                          AirportObject airport = gson.fromJson(reader, AirportObject.class);
                          airp.add(airport);

                    }

                    reader.endArray();
                    reader.close();

                }

                 subscriber.onCompleted();
               }
             catch (IOException e)
             {
                e.printStackTrace();
             }


        }
    }).subscribeOn(Schedulers.newThread())
            .subscribe(new Subscriber<String>() {

                public void onCompleted()
                {
                    Log.wtf("on complete","On complete");
                }

                @Override
                public void onError(Throwable e)
                {
                    e.printStackTrace();
                }

                @Override
                public void onNext(final String progress) {

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                     Log.d("%",progress);
                                }
                        });


                }
            });
}

但是我遇到了这个问题:如果我使用我在评论中添加的代码(字节数组和for循环),它是如此之慢但是它可以工作,如果我使用代码我&# 39; ve post down,当我打印文件大小的日志时,我给出了这个错误:

D/length: 25767936
D/str: 24672558

其中lenght是我在缓存中创建的文件的维度,str是下载的维度。所以我在Gson中给出了MalformedJson的错误。

我该如何解决此错误?

1 个答案:

答案 0 :(得分:0)

根据OP,这一行:

count = inputStream.read(buffer);

应该是:

count = inputStream.read(buffer,0,count);