標籤:讀取 檔案操作 read 關閉 print end main pos cep
字元流
位元組流提供了處理任何類型輸入/輸出操作的功能(因為對於電腦而言,一切都是0和1,只需把資料以位元組形式表示就夠了),但它們不可以直接操作Unicode字元,因為上一篇文章寫了,一個Unicode字元佔用2個位元組,而位元組流一次只能操作一個位元組。既然Java的口號就是"一次編寫、處處運行",那麼包含直接的字元輸入/輸出的支援是必要的。因此就有一些字元輸入/輸出流,之前已經說明過了,字元流頂層是Reader和Writer這兩個抽象類別,因此就從這裡開始本文。
Reader
Reader是定義Java的字元輸入資料流的抽象類別,該類的所有方法在出錯的情況下都將引發IOException。Reader類中有這些方法:
| 方 法 |
作 用 |
| abstract void close() |
關閉該流並釋放與之關聯的所有資源 |
| void mark(int readAheadLimit) |
標記流中的當前位置 |
| boolean markSupported() |
判斷此流是否支援mark()操作 |
| int read() |
從檔案中讀取單個字元 |
| int read(char[] cbuf) |
從檔案中讀取字元到cbuf |
| abstract int read(char[] cbuf, int off, int len) |
將檔案中的字元讀入cbuf數組,從off位置開始,讀取len個字元。三個read方法在字元可用、發生I/O異常或者已經到達流的末尾前,此方法會一直阻塞 |
| int read(CharBuffer target) |
試圖將檔案中的字元讀入指定的字元緩衝區 |
| boolean ready() |
判斷是否準備讀取此流 |
| voi reset() |
重設該流 |
| long skip(long n) |
跳過n個字元 |
Writer
Writer是定義字元輸出資料流的抽象類別,所有該類的方法都返回一個void值並在出錯的條件下引發IOException。Writer類中的方法有:
| 方 法 |
作 用 |
| Writer append(char c) |
將制定字元添加到此writer |
| Writer append(CharSequence csq) |
將制定字元序列添加到此writer |
| Writer append(CharSequence csq, int start, int end) |
將指定字元序列的子序列添加到此writer.Appendable |
| abstract void close() |
關閉此流,但要先flush()它 |
| abstract void flush() |
重新整理該流的緩衝 |
| void write(char[] cbuf) |
將cbuf中的內容寫入檔案 |
| abstract void write(char[] cbuf, int off, int len) |
將字元數組cbuf中從off開始的len個位元組寫入檔案 |
| void write(int c) |
寫入單個字元到檔案中 |
| void write(String str) |
寫入字串到檔案中 |
| void write(String str, int off, int len) |
寫入str從off位置開始的len個字元到檔案中 |
FileReader和FileWriter
FileReader類建立了一個可以讀取檔案內容的Reader類,最常用的構造方法是:
1、FileReader(String fileName)
2、FileReader(File file)
FileWriter建立了一個可以寫檔案的Writer類,最常用的構造方法是:
1、FileWriter(String fileName)
2、FileWriter(String fileName, boolean append)
3、FileWriter(File file)
其中第二個構造方法,如果append為true,那麼輸出是追加到檔案結尾的。FileWriter類的建立不依賴檔案是否存在,在建立檔案之前,FileWriter將在建立對象時開啟它來作為輸出。如果試圖開啟一個唯讀檔案,那麼將引發一個IOException。看一下FileWriter和FileReader的使用,現在D盤目錄下沒有"writer.txt":
public static void main(String[] args) throws Exception{ File file = new File("D:/writer.txt"); Writer out = new FileWriter(file); // 聲明一個String類型對象 String str = "Hello World!!!"; out.write(str); out.close(); // 讀檔案操作 Reader in = new FileReader(file); // 開闢一個空間用於接收檔案讀進來的資料 char c0[] = new char[1024]; int i = 0; // 將c0的引用傳遞到read()方法之中,同時此方法返回讀入資料的個數 i = in.read(c0); in.close(); if (-1 == i) { System.out.println("檔案中無資料"); } else { System.out.println(new String(c0, 0, i)); }}
利用FileWriter和FileReader進行了一次的讀寫操作,先看一下D盤下是否有"writer.txt",假如有"writer.txt"那"writer.txt"中又是什麼:
看來利用FileWriter寫入一個記憶體中的字串到檔案中是成功了,那麼利用利用FileReader讀入檔案中的內容到記憶體呢,看一下運行結果:
Hello World!!!
列印結果和檔案中的內容一致,說明FileReader的操作也成功。
這就是FileWriter和FileReader的使用,和FileOutputStream和FileInputStream的使用差不多,不過實際操作中一般不會用FileWriter和FileReader
JAVA基礎——IO流字元流