簡體   English   中英

Java InputStreamReader和UTF-8字符集

[英]Java InputStreamReader & UTF-8 charset

我使用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()));

閱讀器/書寫器類旨在與文本(基於字符)的輸入/輸出一起使用。

壓縮圖像是二進制的,您需要使用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();
            }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM