轉換流 轉換輸出流 OutputStreamWriter:
說明:
- /*
- * OutputStreamWriter 這個類的作用
- * 就是指定輸出流的編碼格式
- * 這個類的構造方法 需要傳遞 一個輸出流的對象
- * FileOutputStream fos = new FileOutputStream("e:gu.txt");
- * OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
- *
- *
- * */
代碼:
- public static void main(String[] args)throws Exception {
- //創建一個字節輸出流的對象
- FileOutputStream stream = new FileOutputStream("e:gu.txt");
- //創建轉換流的對象
- OutputStreamWriter osw = new OutputStreamWriter(stream,"utf-8"); //第二個參數如果不寫就默認Gbk格式
- osw.write("古斌牛逼");
- osw.close();
- }
運行結果:
轉換流 字節輸入流轉換 InputStreamReader:
說明:
- /*
- * 這個類 InputstreamReader 是用於讀取 指定字符編碼格式的文本
- * 操作方式:
- * 1.創建字節輸入流的對象
- * FileinputStream fis = new FileinputStream("E:gu.txt");
- * 2.創建字節讀取轉換流的對象
- * InputStreamReader isr = new InputStreamReader("fis","utf-8");
- * 注意:
- * 如果你文本的編碼 與要讀取的編碼不一致 會發生讀取到亂碼
- * */
代碼:
- public static void main(String[] args)throws Exception {
- FileInputStream fis = new FileInputStream("E:gu.txt"); //創建字節輸入流對象
- //創建字節輸入轉換流的對象
- InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
- char[] c = new char[1024];
- int len = 0;
- while((len = isr.read(c))!=-1) {
- System.out.println(new String(c, 0, len));
- }
- //關閉數據流
- isr.close();
- }
運行結果: