“你好,阿米戈!昨天 Rishi 向你介紹了FileInputStream和FileOutputStream。今天我將向你介紹FileReader和FileWriter類。”
正如您可能已經猜到的那樣,所有這些類都是 File 對象與 InputStream 、 OutputStream 、 Reader和Writer «接口» 之間的適配器。
“它們類似於 File 和 Reader/Writer 之間的適配器,但您只需要將 String 對像傳遞給構造函數,而不是 File!”
“實際上,它們有幾個構造函數。File 和 String 對像都有構造函數。如果你將一個 String 對像傳遞給構造函數,那麼構造函數將使用從傳遞的 String 對像中獲取的文件路徑悄悄地創建一個 File 對象。”
這是為了方便。Java 的創建者採用了這些類最常見的用例,並為所有這些類編寫了構造函數。這很方便,你不覺得嗎?
“哦,是的。方便。我同意。但為什麼我必須不斷地寫:”
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
“他們為什麼不添加這個用例?”
“這裡的問題是 典型的 Java 程序不能在控制台上運行。事實上,你幾乎從不從它讀取任何東西。即使是在網絡服務器、應用程序服務器或其他一些複雜的系統上也是如此。”
但是我們確實有 PrintStream 用於將數據和文本輸出到控制台。因為這些“服務器應用程序”經常使用控制台來顯示它們的狀態、錯誤和各種其他信息。
“知道了。您還可以使用 FileReader 和 FileWriter 複製文件嗎?”
“是的,如果它是一個文本文件(即它由字符組成)。這是一個例子:”
public static void main(String[] args) throws Exception
{
FileReader reader = new FileReader("c:/data.txt");
FileWriter writer = new FileWriter("c:/result.txt");
while (reader.ready()) //as long as there are unread bytes in the input stream
{
int data = reader.read(); //Read one character (the char will be widened to an int)
writer.write(data); //Write one character (the int will be truncated/narrowed to a char)
}
//Close the streams after we done using them
reader.close();
writer.close();
}
“幾乎沒有區別。”
“是的,差異很小。”
GO TO FULL VERSION