IO流之其它流
阿新 • • 發佈:2021-07-16
IO流之其它流
轉換流
- 屬於字元流(InputStreamReader/OutputStreamWriter)
- InputStreamReader:將一個位元組的輸入流流轉換為字元的輸入流
- OutputStreamWriter:將一個字元的輸出流轉換為位元組的輸出流
- 作用:提供位元組流和字元流之間的轉換
InputStreamReader
package com.yicurtain.IO; import org.junit.Test; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class TransformStreamTeat { //將位元組流,轉換為字元流 @Test public void test1(){ FileInputStream fis = null; InputStreamReader isr = null; try { fis = new FileInputStream("科技英語.txt"); isr = new InputStreamReader(fis,"UTF-8"); char[] data = new char[30]; int len; while ((len=isr.read(data))!=-1){ String str = new String(data,0,len); System.out.println(str); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (isr!=null) isr.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fis!=null) fis.close(); } catch (IOException e) { e.printStackTrace(); } } } }
OutputStreamWriter
實現圖片所示過程
@Test public void test2(){ InputStreamReader isr = null; OutputStreamWriter osw = null; try { File file1 = new File("科技英語.txt"); File file2 = new File("科技英語_gbk.txt"); FileInputStream fis = new FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2); isr = new InputStreamReader(fis,"utf-8"); osw = new OutputStreamWriter(fos,"gbk"); char[] cbuf=new char[20]; int len; while ((len=isr.read(cbuf))!=-1){ osw.write(cbuf,0,len); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (isr!=null) isr.close(); } catch (IOException e) { e.printStackTrace(); } try { if (osw!=null) osw.close(); } catch (IOException e) { e.printStackTrace(); } } }
常見的編碼表
- ASCII:美國標準資訊交換碼。
用一個位元組的7位可以表示。 - ISO8859-1:拉丁碼錶。歐洲碼錶
用一個位元組的8位表示。 - GB2312:中國的中文編碼表。最多兩個位元組編碼所有字元
- GBK:中國的中文編碼表升級,融合了更多的中文文字元號。最多兩個位元組編碼
- Unicode:國際標準碼,融合了目前人類使用的所有字元。為每個字元分配唯一的
字元碼。所有的文字都用兩個位元組來表示。 - UTF-8:變長的編碼方式,可用1-4個位元組來表示一個字元。
標準的輸入輸出流(瞭解)
- System.in:標準的輸入流;預設從鍵盤輸入
- System.out:標準的輸出流;預設從控制檯輸出
列印流(瞭解)
- PrintStream
- PrintWriter
資料流(瞭解)
- DataInputStream
- DataOutputStream
- 作用:用於讀取或寫出基本資料型別的變數或字串
p605