開始使用免費開始

有效率地處理長筆記

當使用者撰寫較長的筆記時,效能就很重要。Java 的緩衝類別能有效率地讀寫大量文字。在這個練習中,你將使用 BufferedReaderBufferedWriter 來處理儲存在 "note.txt" 的筆記。

java.io 中所需的套件都已為你匯入。

本練習屬於課程

Java 的輸入/輸出與串流

檢視課程

練習說明

  • 透過將 FileWriter(以檔名 "note.txt" 建立)包起來,建立名為 bwBufferedWriter 實例。
  • 將第一行文字 "This is the first line" 寫入檔案,接著使用 .newLine() 加入換行,並寫入第二行文字 "This is the second line"
  • 透過將 FileReader 包起來,建立名為 brBufferedReader 實例來讀取 "note.txt"
  • 逐行讀取檔案。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class FileOperations {

    public static void main(String[] args) {
        try {
            // Create a new instance of BufferedWriter
            BufferedWriter bw = ____ ____(new FileWriter("note.txt"));

            // Write the text, "This is the first line"
            bw.____("This is the first line");

            // Add a new line
            bw.____();

            // Write the second line of text, "This is the second line"
            bw.____("This is the second line"); 
            
            bw.close();

            // Create a new instance of BufferedReader
            BufferedReader br = ____ ____(new FileReader("note.txt"));
            String line;
            while ((line = br.____()) != null) {
                System.out.println(line);
            }

            // Close the BufferedReader
            br.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
編輯並執行程式碼