InputStream 、 InputStreamReader 、 BufferedReader區別

區別介紹:
1、InputStream、OutputStream

處理字節流的抽象類

InputStream 是字節輸入流的所有類的超類,一般我們使用它的子類,如FileInputStream等.

OutputStream是字節輸出流的所有類的超類,一般我們使用它的子類,如FileOutputStream等.

 

2、InputStreamReader  OutputStreamWriter

處理字符流的抽象類

InputStreamReader 是字節流通向字符流的橋樑,它將字節流轉換爲字符流.

OutputStreamWriter是字符流通向字節流的橋樑,它將字符流轉換爲字節流.

 

3、BufferedReader BufferedWriter

BufferedReader 由Reader類擴展而來,提供通用的緩衝方式文本讀取,readLine讀取一個文本行,

從字符輸入流中讀取文本,緩衝各個字符,從而提供字符、數組和行的高效讀取。

BufferedWriter  由Writer 類擴展而來,提供通用的緩衝方式文本寫入, newLine使用平臺自己的行分隔符,

將文本寫入字符輸出流,緩衝各個字符,從而提供單個字符、數組和字符串的高效寫入。

==============================================================

E:/baoyue13.txt 文件內容:

123456789abcdefg
235xyz

附代碼:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileInputStreamDemo {
    public static void main(String[] args) throws Exception {

        /**
         * InputStream能從來源處讀取一個一個byte,所以它是最低級的,
         */

        // read()方法返回的int類型,是表示數據下一個字節的字節碼,如果已經到達流的最後面了,那就返回-1
        // 通過char 強轉,輸出字節碼的內容
        FileInputStream fileIn2 = new FileInputStream(new File("E:/baoyue13.txt"));
        int read = fileIn2.read();
        System.out.println( read);
        System.out.println((char) read);

        byte[] bb = new byte[4];
        int read2 = fileIn2.read(bb);
        System.out.println( "長度 read2: " + read2);
        for(byte b:bb) {
            System.out.println(b);
            System.out.println((char)b);
        }

        int aa;
        while ((aa = fileIn2.read()) != -1) {
            System.out.print((char) aa);
        }

        System.out.println();
        System.out.println("--------------------------------");

        /**
         * InputStreamReader封裝了InputStream在裏頭,它以較高級的方式,一次讀取一個一個字符,
         * 
         */

        FileInputStream fileIn3 = new FileInputStream(new File("E:/baoyue13.txt"));

        InputStreamReader sr = new InputStreamReader(fileIn3);
        System.out.println((char)sr.read());

        int a2;
        while ((a2 = sr.read()) != -1) {
            System.out.print((char) a2);
        }

        System.out.println();
        System.out.println("--------------------------------");

        /**
         * BufferedReader則是比InputStreamReader更高級,
         * 它封裝了StreamReader類,一次讀取取一行的字符
         * 
         */

        FileInputStream fileIn4 = new FileInputStream(new File("E:/baoyue13.txt"));
        InputStreamReader sr2 = new InputStreamReader(fileIn4);
        BufferedReader br=new BufferedReader(sr2); 

        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

    }

}

執行結果:

49
1
長度 read2: 4
50
2
51
3
52
4
53
5
6789abcdefg
235xyz
--------------------------------
1
23456789abcdefg
235xyz
--------------------------------
123456789abcdefg
235xyz
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章