Scanner、BufferedReader、InputStreamReader等的區別
- Scanner
是一個可以使用正則表示式來分析基本型別和字串的簡單文字掃描器!也就是控制檯應用程式最為常用的文字輸入方式!Scanner取得輸入資料的依據是空格符:如按下空格鍵,Tab鍵或者Enter鍵,Scanner就會返回下一個輸入。所以說Scanner不能輸入空格,如果你希望取得含有空格的字串BufferedReader可以做到。
- InputStream、OutputStream
處理位元組流的抽象類
InputStream 是位元組輸入流的所有類的超類,一般我們使用它的子類,如FileInputStream等.
OutputStream是位元組輸出流的所有類的超類,一般我們使用它的子類,如FileOutputStream等.
- InputStreamReader OutputStreamWriter
處理字元流的抽象類
InputStreamReader 是位元組流通向字元流的橋樑,它將位元組流轉換為字元流.
OutputStreamWriter是字元流通向位元組流的橋樑,它將字元流轉換為位元組流.
- BufferedReader BufferedWriter
BufferedReader 由Reader類擴充套件而來,提供通用的緩衝方式文字讀取,readLine讀取一個文字行,
從字元輸入流中讀取文字,緩衝各個字元,從而提供字元、陣列和行的高效讀取。
BufferedWriter 由Writer 類擴充套件而來,提供通用的緩衝方式文字寫入, newLine使用平臺自己的行分隔符,
將文字寫入字元輸出流,緩衝各個字元,從而提供單個字元、陣列和字串的高效寫入。
InputStream能從來源處讀取一個一個byte,
所以它是最低階的, 例:
import <a href="http://lib.csdn.net/base/javase" class='replace_word' title="Java SE知識庫" target='_blank' style='color:#df3434; font-weight:bold;'>Java</a>.io.*; public class Main { public static void main(String[] args) { try { FileInputStream fis=new FileInputStream("d://desktop//test.txt"); int i; try { while((i=fis.read()) != -1){ System.out.println(i); } /*假設test.txt檔裡頭只有一個文字 "陳" ,且其編碼為 utf8 * 輸出 * 233 153 179 */ } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
- InputStreamReader
InputStreamReader封裝了InputStream在裡頭, 它以較高階的方式,一次讀取一個一個字元, 下例是假設有一個編碼為utf8的文件, 其內容只有一箇中文字 "陳"
import java.io.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
FileInputStream fis=new FileInputStream("d://desktop//test.txt");
try {
InputStreamReader isr=new InputStreamReader(fis,"utf8");
int i;
while((i=isr.read()) != -1){
System.out.println((char)i); //輸出 陳
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
BufferedReader BufferedReader則是比InputStreamReader更高階, 它封裝了StreamReader類, 一次讀取取一行的字元
import java.io.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
FileInputStream fis=new FileInputStream("d://desktop//test.txt");
try {
InputStreamReader isr=new InputStreamReader(fis,"utf8");
BufferedReader br=new BufferedReader(isr);
String line;
while((line=br.readLine()) != null){
System.out.println(line);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}