简体   繁体   中英

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()));

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();
            }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM