Unable to read all bytes using InputStream read API?

拈花ヽ惹草 提交于 2021-02-05 11:34:31

问题


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. It works very fine, when i tested through iOS simulator. Because, If I test in simulator, it sends the image upto 46,577 bytes. It reads all very quickly and properly. If I test the same code sending image from an iPhone device, its also sending around "45, 301 bytes", but socket code is able to read only some "21, 720 bytes", so only half of the image is coming, (or) sometimes it reads very less around "4,000 bytes" only.

I couldn't understand why it is not able to read the same size data coming from device only? Could someone please guide me on this to solve?

InputStream input = socket.getInputStream();

            byte[] data = new byte[0];
            byte[] buffer = new byte[1024];             

            try {
                do {
                bytesRead = input.read(buffer);
                System.out.println("Reading..bytesRead: " + bytesRead);

                // construct an array large enough to hold the data we currently have
                byte[] newData = new byte[data.length + bytesRead];
                // copy data that was previously read into newData
                System.arraycopy(data, 0, newData, 0, data.length);
                // append new data from buffer into newData
                System.arraycopy(buffer, 0, newData, data.length, bytesRead);
                // set data equal to newData in prep for next block of data
                data = newData;

                } while (input.available() != 0);
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }

            System.out.println("data: " + data.length);

回答1:


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.



来源:https://stackoverflow.com/questions/21718736/unable-to-read-all-bytes-using-inputstream-read-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!