java - Reading char[] from web-service by HttpGet — strange behavior -


i developing android application, going fetch big chunk of json data in stream. calling web service ok, have little problem. in old version using gson reading stream i've tried insert data database, ok without problem except performance. tried change approach of loading data, trying read data char[] first insert them database.

this new code:

httpentity responseentity = response.getentity(); final int contentlength = (int) responseentity.getcontentlength(); inputstream stream = responseentity.getcontent(); inputstreamreader reader = new inputstreamreader(stream);  int readcount = 10 * 1024; int hasread = 0; char[] buffer = new char[contentlength]; int mustwrite = 0; int hasread2 = 0; while (hasread < contentlength) {     // problem here     hasread += reader.read(buffer, hasread, contentlength - hasread); }  reader reader2 = new chararrayreader(buffer); 

the problem reader starts reading correctly @ near of end of stream, hasread variable value decreases (by 1) instead of increasing. strange me, , while loop never finishes. what's wrong code?

you should use fixed size buffer, not size of whole data (the contentlength). , important note: length of char[] array different byte[] array's. char data type single 16-bit unicode character. while byte data type 8-bit signed two's complement integer.

also while loop wrong, can fix as:

import java.io.bufferedinputstream;  private static final int buf_size = 10 * 1024;  // ...  httpentity responseentity = response.getentity(); final int contentlength = (int) responseentity.getcontentlength(); inputstream stream = responseentity.getcontent(); bufferedinputstream reader = new bufferedinputstream(stream);  int hasread = 0; byte[] buffer = new byte[buf_size]; while ((hasread = reader.read(buffer, 0, buf_size)) > 0) {     // example, convert buffer string     string data = new string(buffer, 0, hasread, "utf-8"); } 

make sure use own charset ("utf-8", "utf-16"…).


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -