40、使用位元組流讀取檔案亂碼問題
阿新 • • 發佈:2018-12-19
寫出中文
向txt檔案中寫出中文,通過下面程式碼的演示,因為一箇中文佔2個位元組,所以按照位元組寫出中文時會出現亂碼的情況。
package com.sutaoyu.IO; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class IO_test_6 { public static void main(String[] args) { FileOutputStream fos = null;try{ fos = new FileOutputStream("word.txt"); String msg = "好好學習"; //fos.write(msg.getBytes()); //每次寫出3個位元組,因為一箇中文佔用2個位元組,所以導致亂碼 fos.write(msg.getBytes(),0,3); //換行 fos.write("\r\n".getBytes()); fos.write("天天向上".getBytes()); fos.flush(); }catch(FileNotFoundException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); } } }
讀取中文
從txt檔案中讀取檔案,下面程式碼也出現了亂碼問題
package com.sutaoyu.IO; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException;public class IO_test_7 { public static void main(String args) throws IOException { FileInputStream fis = null; try { fis = new FileInputStream("word.txt"); byte[] arr = new byte[3]; int temp; while((temp = fis.read(arr)) != -1) { System.out.println(new String(arr,0,temp)); } }catch(FileNotFoundException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); } } }