简体   繁体   English

Java InputStreamReader和UTF-8字符集

[英]Java InputStreamReader & UTF-8 charset

I use InputStreamReader to transfer compressed images. 我使用InputStreamReader传输压缩图像。 InflaterInputStream is used for decompression of images InflaterInputStream用于解压缩图像

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 并且图像损坏了http://s019.radikal.ru/i602/1205/7c/9df90800fba5.gif

With the transfer of uncompressed images I use BufferedReader and everything is working fine 通过传输未压缩的图像,我使用了BufferedReader,并且一切正常

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. 压缩图像是二进制的,您需要使用InputStream / OutputStream或nio类来传输二进制数据。

An example using InputStream/OutputStream is given below. 下面给出了使用InputStream / OutputStream的示例。 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();
            }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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