Unable to read all bytes using InputStream read API?

前端 未结 1 1210
忘了有多久
忘了有多久 2021-01-27 06:42

I am having problem reading image bytes in java socket. My iOS client is sending an image here, and it needs to read the total bytes and store that as image on the server end. <

相关标签:
1条回答
  • 2021-01-27 07:28

    You're misusing available(). It is not valid as a test for end of stream. See the Javadoc.

    You don't need all that array copying either. Try this:

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    while ((count = in.read(buffer)) > 0)
    {
        out.write(buffer, 0, count);
    }
    byte[] data = out.toByteArray();
    

    If you're storing the image at the receiving end you should just write direct to a FileOutputStream instead of the ByteArrayOutputStream above, and forget about data altogether.

    0 讨论(0)
提交回复
热议问题