1

Just trying to keep the reading as simple as possible. However, the while loop seems to return after 1 loop.

try {
   final int SIZE = 512;

   byte[] buffer = new byte[SIZE];
   int bytesRead = 0;

   while(inputStream.read(buffer) != -1) {
       bytesRead++;
   }

   jsonString = buffer.toString();
   System.out.println("bytesRead: " + bytesRead + " [ " + jsonString + " ]");
}

It should return something like this:

{"errCode":"7500","errDesc":"unknown"}

But when I get printed out is this:

bytesRead: 1 [ [B@5361bf4c ]

Seems it prints out an memory address or just rubbish.

If I use the following:

inputStream.read(buffer, 0, SIZE);

I get the following:

bytesRead: 0 [ [B@53623578 ]

Many thanks for any advice,

ant2009
  • 27,094
  • 154
  • 411
  • 609
  • 2
    `buffer.toString()` doesn't do what you think, it doesn't convert from `byte[]` to `String` it only prints a string representation of the object – morgano Jul 03 '14 at 02:52
  • @Takendarkk, I have put the while loop back. Just testing and forgot. – ant2009 Jul 03 '14 at 02:53
  • 1
    Replace `buffer.toString()` with `new String(buffer, "ASCII")` or whatever the encoding you're using – morgano Jul 03 '14 at 02:54
  • @morgano, But it should read into the buffer more than 1 byte. There should be at least 60 bytes to read into it. – ant2009 Jul 03 '14 at 02:54
  • Thats what happens wheb you try to print an object (an array is an object). I think what you wanna do is take the bytes from the buffer and turn them into chars so you can create a String (assuming thats what you're trying to receive) – Vince Jul 03 '14 at 02:55
  • @ant2009 this is one is better i think http://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/ – Kick Buttowski Jul 03 '14 at 03:00
  • @ant2009 No. The read() method isn't obliged to transfer more than one byte. See the Javadoc. – user207421 Jul 03 '14 at 03:02
  • @morgano, You was correct. Can you put your solution as an answer so I can mark it correct. – ant2009 Jul 03 '14 at 03:07
  • @ant2009 Thanks for your intention, but it doesn't matter; also, the question has been marked as duplicate, so no new answers are allowed – morgano Jul 03 '14 at 03:10
  • Actually he wasn't correct. It should have been 'new String(buffer, 0, count, "ASCII")', where 'count' was the result returned by 'read()'. – user207421 Jul 03 '14 at 03:14
  • See also http://stackoverflow.com/questions/7060016/why-does-the-tostring-method-in-java-not-seem-to-work – Raedwald Jul 07 '14 at 23:39

0 Answers0