1. 程式人生 > >轉換流和標準輸入和輸出流

轉換流和標準輸入和輸出流

轉換流提供了字元流和位元組流之間的轉換

InputStreamReader和OutputStreamWriter

位元組流中的資料都是字元時,轉成字元流操作更高效

/*
轉換流:inputStreamReader OutputStreamWriter
編碼:字串  ---> 位元組陣列
       位元組陣列 ---> 字串
 */
@Test
public void test1(){
    //解碼
    BufferedReader br =null;
    BufferedWriter bw = null;
    try {
        File file =
new File("a.txt"); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, "GBK"); br = new BufferedReader(isr); //編碼 File file2 = new File("a5.txt"); FileOutputStream fos = new FileOutputStream(file2); OutputStreamWriter osw =
new OutputStreamWriter(fos); bw = new BufferedWriter(osw); String str; while ((str = br.readLine())!=null){ bw.write(str); bw.newLine(); bw.flush(); } } catch (IOException e) { e.printStackTrace(); }finally { if
(bw != null){ try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } if (br!= null){ try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }

標準輸入輸出流

/*
標準的輸入輸出流
題目:從鍵盤中輸入字串,要求讀取到整行字串轉換成大寫輸出
直到輸入"e"或"exit"時,退出程式
 */
@Test
public void test2(){
    BufferedReader br = null;
    try {
        InputStream is = System.in;
        InputStreamReader isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String str ;
        while (true){
            System.out.println("請輸入字串:");
            str = br.readLine();
            if (str.equalsIgnoreCase("e") || str.equalsIgnoreCase("exit")){
                break;
            }
            String str1 = str.toUpperCase();
            System.out.println(str1);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (br!=null){
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

編碼表的由來

計算機只能識別二進位制資料,早期由來是電訊號。為了方便應用計算機,讓它可以識別各個國家的文字。就將各個國家的文字用數字來表示,並一一對應,形成一張表。這就是編碼表。
編碼表的由來
計算機只能識別二進位制資料,早期由來是電訊號。為了方便應用計算機,讓它可以識別各個國家的文字。就將各個國家的文字用數字來表示,並一一對應,形成一張表。這就是編碼表。

常見的編碼表

ASCII:美國標準資訊交換碼。
用一個位元組的7位可以表示。
ISO8859-1:拉丁碼錶。歐洲碼錶
用一個位元組的8位表示。
GB2312:中國的中文編碼表。
GBK:中國的中文編碼表升級,融合了更多的中文文字元號。
Unicode:國際標準碼,融合了多種文字。
所有文字都用兩個位元組來表示,Java語言使用的就是unicode
UTF-8:最多用三個位元組來表示一個字元。