解析IO操作InputStream、OutputStream、InputStreamReader OutputStreamWriter、BufferedReader BufferedWriter

李小妖ldl發表於2020-11-09

1、InputStream、OutputStream
處理位元組流的抽象類
InputStream 是位元組輸入流的所有類的超類,一般我們使用它的子類,如FileInputStream等.
OutputStream是位元組輸出流的所有類的超類,一般我們使用它的子類,如FileOutputStream等.

//以下是FileInputStream讀取檔案輸出列印為例
String path = "D:/789.txt";
File file = new File(path);

StringBuffer stringBuffer1 = new StringBuffer();

FileInputStream fileInputStream = new FileInputStream(file);
int index;
while((index = fileInputStream.read()) != -1){
    char strChar = (char)index;
    stringBuffer1.append(strChar);
}
System.out.println(stringBuffer1.toString());
fileInputStream.close();

2.InputStreamReader OutputStreamWriter
處理字元流的抽象類
InputStreamReader 是位元組流通向字元流的橋樑,它將位元組流轉換為字元流.
OutputStreamWriter是字元流通向位元組流的橋樑,它將字元流轉換為位元組流.

//以下是InputStreamReader讀取檔案輸出列印為例
String path = "D:/789.txt"; 
File file = new File(path);
StringBuffer stringBuffer2 = new StringBuffer();
 
FileInputStream fileInputStream = new FileInputStream(file);
//處理中文亂碼 設定utf-8
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
int index;
while((index = inputStreamReader.read()) != -1){
    char strChar = (char)index;
    stringBuffer2.append(strChar);
}
System.out.println(stringBuffer2.toString());
inputStreamReader.close();
fileInputStream.close();

3.BufferedReader BufferedWriter
BufferedReader 由Reader類擴充套件而來,提供通用的緩衝方式文字讀取,readLine讀取一個文字行,
從字元輸入流中讀取文字,緩衝各個字元,從而提供字元、陣列和行的高效讀取。
BufferedWriter 由Writer 類擴充套件而來,提供通用的緩衝方式文字寫入, newLine使用平臺自己的行分隔符,
將文字寫入字元輸出流,緩衝各個字元,從而提供單個字元、陣列和字串的高效寫入。

String path = "D:/789.txt";
File file = new File(path);
//以下是BufferedReader讀取檔案輸出列印為例 
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
 
StringBuffer stringBuffer3 = new StringBuffer();
String str;
while((str = bufferedReader.readLine()) != null){
    stringBuffer3.append(str);
}
System.out.println(stringBuffer3.toString());
bufferedReader.close();
inputStreamReader.close();
fileInputStream.close();

相關文章