Java InputStreamReader& UTF-8字符集

时间:2012-05-24 18:19:07

标签: java utf-8 character inputstreamreader

我使用InputStreamReader传输压缩图像。 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);

但所有非拉丁字符都变成“?”并且图像被破坏http://s019.radikal.ru/i602/1205/7c/9df90800fba5.gif

通过传输未压缩的图像,我使用BufferedReader,一切正常

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

1 个答案:

答案 0 :(得分:5)

Reader / Writer类旨在使用文本(基于字符)输入/输出。

压缩图像是二进制的,您需要使用InputStream / OutputStream或nio类来传输二进制数据。

下面给出了使用InputStream / OutputStream的示例。此示例将接收的数据存储在本地文件中:

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