標籤:返回 字元流 append app int 構造 重新整理方法 reader 目的
一.FileReader類
1,構造方法:
FileReader fr = new FileReader(String fileName);//使用帶有指定檔案的String參數的構造方法。建立該輸入資料流對象。並關聯源檔案。
2,主要方法:
int read(); // 讀取單個字元,返回一個int型變數代表讀取到的字元,如果已達到流末尾,則返回 -1。
int read(char []cbuf);//將字元讀入數組。返回讀取的字元數。如果已經到達尾部,則返回-1。
void close();//關閉此流對象。釋放與之關聯的所有資源。
例,
3.FileReader讀取檔案內容
①方法一:
try{
//FileReader類從InputStreamReader類繼承而來。該類按字元讀取流中資料。
FileReader inread=new FileReader("E:\\xxx\\1\\BeautifulSoup總結.txt");
//讀取字元流
BufferedReader in=new BufferedReader(inread);
//BufferedReader in=new BufferedReader(new FileReader("E:\\xxx\\test.txt"));
String str;//用來儲存讀取到的檔案內容
while((str=in.readLine())!=null){
System.out.println(str);
}
System.out.println(str);
}catch(Exception e){
e.printStackTrace();
}
②方法二
try{
FileReader read=new FileReader("E:\\xxx\\test.txt");
int ch = 0;
//read()讀取單個字元,返回一個int型變數代表讀取到的字元
while((ch = read.read()) != -1){
System.out.print((char)ch);
}
read.close();
}catch(Exception e){
e.printStackTrace();
}
二,FileWriter類(字元輸出資料流類)
1,構造方法:
FileWriter fw = new FileWriter(String fileName);//建立字元輸出資料流類對象和已存在的檔案相關聯。檔案不存在的話,並建立。
如:FileWriter fw = new FileWriter("C:\\demo.txt");
FileWriter fw = new FileWriter(String fileName,boolean append);//建立字元輸出資料流類對象和已存在的檔案相關聯,並設定該該流對檔案的操作是否為續寫。
如:FileWriter fw = new FileWriter("C:\\demo.txt",ture); //表示在fw對檔案再次寫入時,會在該檔案的結尾續寫,並不會覆蓋掉。
2,主要方法:
void write(String str) //寫入字串。當執行完此方法後,字元資料還並沒有寫入到目的檔案中去。此時字元資料會儲存在緩衝區中。
此時在使用重新整理方法就可以使資料儲存到目的檔案中去。
viod flush() //重新整理該流中的緩衝。將緩衝區中的字元資料儲存到目的檔案中去。
viod close() //關閉此流。在關閉前會先重新整理此流的緩衝區。在關閉後,再寫入或者重新整理的話,會拋IOException異常。
例,
3.FileWriter()想檔案追加內容
try{
//new FileWriter(filename,true):true表示以追加的形式寫入,沒有true則會覆蓋原有的內容
BufferedWriter writer=new BufferedWriter(new FileWriter("E:\\xxx\\test.txt",true));
writer.write("yxy");
writer.flush();
writer.close();//必須執行
}catch(Exception e){
e.printStackTrace();
}
Java的 FileWriter類 和 FileReader類