Java - io輸入輸出流 --轉換流


 

轉換流  轉換輸出流 OutputStreamWriter:

說明:

 

  1. /*
  2. * OutputStreamWriter 這個類的作用
  3. * 就是指定輸出流的編碼格式
  4. * 這個類的構造方法 需要傳遞 一個輸出流的對象
  5. * FileOutputStream fos = new FileOutputStream("e:gu.txt");
  6. * OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
  7. *
  8. *
  9. * */

代碼:

   

  1. public static void main(String[] args)throws Exception {
  2. //創建一個字節輸出流的對象
  3. FileOutputStream stream = new FileOutputStream("e:gu.txt");
  4. //創建轉換流的對象
  5. OutputStreamWriter osw = new OutputStreamWriter(stream,"utf-8"); //第二個參數如果不寫就默認Gbk格式
  6. osw.write("古斌牛逼");
  7. osw.close();
  8. }

 

 運行結果:

 

轉換流  字節輸入流轉換 InputStreamReader

 

 

 說明:

  1. /*
  2. * 這個類 InputstreamReader 是用於讀取 指定字符編碼格式的文本
  3. * 操作方式:
  4. * 1.創建字節輸入流的對象
  5. * FileinputStream fis = new FileinputStream("E:gu.txt");
  6. * 2.創建字節讀取轉換流的對象
  7. * InputStreamReader isr = new InputStreamReader("fis","utf-8");
  8. * 注意:
  9. * 如果你文本的編碼 與要讀取的編碼不一致 會發生讀取到亂碼
  10. * */

  代碼:

  1. public static void main(String[] args)throws Exception {
  2. FileInputStream fis = new FileInputStream("E:gu.txt"); //創建字節輸入流對象
  3. //創建字節輸入轉換流的對象
  4. InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
  5. char[] c = new char[1024];
  6. int len = 0;
  7. while((len = isr.read(c))!=-1) {
  8. System.out.println(new String(c, 0, len));
  9. }
  10. //關閉數據流
  11. isr.close();
  12. }

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM