Search code examples
javaandroidsocketsinputstreamfileinputstream

Reading JPEG Stream over socket gives Null characters


I am reading a .jpg file over InputStream using this code but I am receiving NULNUL...n stream after some text. Ii am reading this file link to file and link of file that I received , link is Written File link.

    while ((ret = input.read(imageCharArray)) != -1) {
    packet.append(new String(imageCharArray, 0, ret));

    totRead += ret;
            imageCharArray = new char[4096];
       }


   file = new File(
     Environment.getExternalStorageDirectory()
       + "/FileName_/"
       + m_httpParser.filename + ".jpg");
   PrintWriter printWriter = new PrintWriter(file);
   // outputStream = new FileOutputStream(file);  //also Used FileoutputStream for writting
   // outputStream.write(packet.toString().getBytes());//
   // ,
   printWriter.write(packet.toString());
   // outputStream.close();
   printWriter.close();
 }

I have also tried FileoutputStream but hardlucj for this too as commented in my code.

Edit I have used this also. I have a content length field upto which i am reading and writing

    byte[] bytes = new byte[1024];
int totalReadLength = 0;

// read untill we have bytes
while ((read = inputStream.read(bytes)) != -1
        && contentLength >= (totalReadLength)) {

    outputStream.write(bytes, 0, read);
    totalReadLength += read;
    System.out.println(" read size ======= "
            + read + " totalReadLength = "
            + totalReadLength);

}

Solution

  • String is not a container for binary data, and PrintWriter isn't a way to write it. Get rid of all, all, the conversions between bytes and String and vice versa, and just transfer the bytes with input and output streams:

    while ((count = in.read(buffer)) > 0)
    {
        out.write(buffer, 0, count);
    }
    

    If you need to constrain the number of bytes read from the input, you have to do that before calling read(), and you also have to constrain the read() correctly:

    while (total < length && (count = in.read(buffer, 0, length-total > buffer.length ? buffer.length: (int)(length-total))) > 0)
    {
        total += count;
        out.write(buffer, 0, count);
    }