Dmitriy
Dmitriy

Reputation: 161

Java InputStreamReader & UTF-8 charset

I use InputStreamReader to transfer compressed images. InflaterInputStream is used for decompression of images

InputStreamReader infis =
   new InputStreamReader(
      new InflaterInputStream( download.getInputStream()), "UTF8" );
do {
   buffer.append(" ");
   buffer.append(infis.read());
} while((byte)buffer.charAt(buffer.length()-1) != -1);

But all non-Latin characters become "?" and the image is broken http://s019.radikal.ru/i602/1205/7c/9df90800fba5.gif

With the transfer of uncompressed images I use BufferedReader and everything is working fine

BufferedReader is =
   new BufferedReader(
      new InputStreamReader( download.getInputStream()));

Upvotes: 0

Views: 4606

Answers (1)

Hakan Serce
Hakan Serce

Reputation: 11256

Reader/Writer classes are designed to work with textual(character based) input/output.

Compressed images are binary, and you need to use either InputStream/OutputStream or nio classes for transferring binary data.

An example using InputStream/OutputStream is given below. This example stores the received data in a local file:

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {

        bis = new BufferedInputStream(download.getInputStream());
        bos = new BufferedOutputStream(new FileOutputStream("c:\\mylocalfile.gif"));

        int i;
        // read byte by byte until end of stream
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
    } finally {
        if (bis != null)
            try {
                bis.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        if (bos != null)
            try {
                bos.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
    }

Upvotes: 5

Related Questions