(本文非原創,轉自http://blog.csdn.net/double2hao/article/details/50321219)
最進在梳理java的文件讀取,讀取文件,當然要理解當中幾個重要的IO流,下面是轉自一片比較清晰的博客。
一.java IO流
1.處理字節流的抽象類: InputStream、OutputStream
InputStream 是字節輸入流的所有類的超類,一般我們使用它的子類,如FileInputStream等.
OutputStream是字節輸出流的所有類的超類,一般我們使用它的子類,如FileOutputStream等.
2.處理字符流的抽象類:InputStreamReader OutputStreamWriter
InputStreamReader 是字節流通向字符流的橋梁,它將字節流轉換為字符流.
OutputStreamWriter是字符流通向字節流的橋梁,它將字符流轉換為字節流.
3.BufferedReader BufferedWriter
BufferedReader 由Reader類擴展而來,提供通用的緩沖方式文本讀取,readLine讀取一個文本行,
從字符輸入流中讀取文本,緩沖各個字符,從而提供字符、數組和行的高效讀取。
BufferedWriter 由Writer 類擴展而來,提供通用的緩沖方式文本寫入, newLine使用平台自己的行分隔符,
將文本寫入字符輸出流,緩沖各個字符,從而提供單個字符、數組和字符串的高效寫入。
代碼:
public class FileIo {
public static void main(String[] args) throws IOException {
//1.按字節讀寫文件,用FileInputStream、FileOutputStream
String path = "D:\\iotest.txt";
File file = new File(path);
InputStream in;
//每次只讀一個字節
try {
System.out.println("以字節為單位,每次讀取一個字節");
in = new FileInputStream(file);
int c;
while((c=in.read())!=-1){
if(c!=13&&c!=10){ // \n回車的Ascall碼是10 ,\r換行是Ascall碼是13,不現實揮着換行
System.out.println((char)c);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//每次讀多個字節
try {
System.out.println("以字節為單位,每次讀取多個字節");
in = new FileInputStream(file);
byte[] bytes = new byte[10]; //每次讀是個字節,放到數組里
int c;
while((c=in.read(bytes))!=-1){
System.out.println(Arrays.toString(bytes));
}
} catch (Exception e) {
// TODO: handle exception
}
//2.按字符讀取文件,用InputStreamReader,OutputStreamReader
Reader reader = null;
try {//每次讀取一個字符
System.out.println("以字符為單位讀取文件,每次讀取一個字符");
in = new FileInputStream(file);
reader = new InputStreamReader(in);
int c;
while((c=reader.read())!=-1){
if(c!=13&&c!=10){ // \n回車的Ascall碼是10 ,\r換行是Ascall碼是13,不現實揮着換行
System.out.println((char)c);
}
}
} catch (Exception e) {
// TODO: handle exception
}
try {//每次讀取多個字符
System.out.println("以字符為單位讀取文件,每次讀取一個字符");
in = new FileInputStream(file);
reader = new InputStreamReader(in);
int c;
char[] chars = new char[5];
while((c=reader.read(chars))!=-1){
System.out.println(Arrays.toString(chars));
}
} catch (Exception e) {
// TODO: handle exception
}
//3.按行讀取文件
try {
System.out.println("按行讀取文件內容");
in = new FileInputStream(file);
Reader reader2 = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(reader2);
String line;
while((line=bufferedReader.readLine())!=null){
System.out.println(line);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
12.4 轉換流--OutputStreamWriter類與InputStreamReader類
整個IO包實際上分為字節流和字符流,但是除了這兩個流之外,還存在一組字節流-字符流的轉換類。
OutputStreamWriter:是Writer的子類,將輸出的字符流變為字節流,即將一個字符流的輸出對象變為字節流輸出對象。
InputStreamReader:是Reader的子類,將輸入的字節流變為字符流,即將一個字節流的輸入對象變為字符流的輸入對象。
以文件操作為例,內存中的字符數據需要通過OutputStreamWriter變為字節流才能保存在文件中,讀取時需要將讀入的字節流通過InputStreamReader變為字符 流。