Java之位元組數組和字串的轉換問題

來源:互聯網
上載者:User

標籤:iso   指定   builder   解決   output   row   NPU   static   while   

今天在使用位元組流複製圖片的時候發現一個問題,就是將位元組數組轉化為字串的時候會出現長度不同的問題.這其實是個錯誤的操作.

 public static void main(String[] args) throws IOException {    // 第一種方式(不會出現問題)    /*FileInputStream fis = new FileInputStream("D:\\美女.jpg");    FileOutputStream fos = new FileOutputStream("F:\\ccc\\美女.jpg");    int len;    while((len = fis.read()) != -1){        fos.write(len);    }    fos.close();    fis.close();*/        // 第二種方式,會出現問題    /*FileInputStream fis = new FileInputStream("D:\\美女.jpg");    byte[] arr = new byte[1024 * 6];    int len;    StringBuilder sb = new StringBuilder();    while((len = fis.read(arr)) != -1){        sb.append(new String(arr,0,len));    }    FileOutputStream fos = new FileOutputStream("F:\\ccc\\美女.jpg");    fos.write(sb.toString().getBytes());    fos.close();    fis.close();*/        // 第三種方式,解決問題    FileInputStream fis = new FileInputStream("D:\\美女.jpg");            byte[] arr = new byte[1024 * 6];    int len;    StringBuilder sb = new StringBuilder();    while((len = fis.read(arr)) != -1){        sb.append(new String(arr,0,len,"ISO-8859-1"));    }    FileOutputStream fos = new FileOutputStream("F:\\ccc\\美女.jpg");    fos.write(sb.toString().getBytes("ISO-8859-1"));    fos.close();    fis.close();}

這個的原因是在使用字元數組讀取圖片將它轉化為String類型的時候使用編輯器預設的編碼方式進行轉換,但是預設的編碼方式(UTF-8或者其他)
會出現亂碼(原因是多個位元組轉化為字元的時候碼錶不認識,會出現?),所以長度會增加很多.而在使用ISO-8859-1的時候它就是一個位元組一個位元組轉化的,下面寫入的
時候又指定編碼,相當於是逆轉,所以沒有出現問題

Java之位元組數組和字串的轉換問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.