標籤: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之位元組數組和字串的轉換問題