开始使用免费开始使用

高效处理长笔记

随着用户编写更长的笔记,性能就变得至关重要。Java 的缓冲类可以高效读写大块文本。在本练习中,您将使用 BufferedReaderBufferedWriter 处理保存在 "note.txt" 中的一条笔记。

来自 java.io 的所有必要包都已为您导入。

本练习是课程的一部分

Java 中的输入/输出与流

查看课程

练习说明

  • 通过为名为 "note.txt" 的文件包装一个 FileWriter,创建一个名为 bwBufferedWriter 实例。
  • 将第一行文本 "This is the first line" 写入文件。然后使用 .newLine() 方法添加换行,再写入第二行文本 "This is the second line"
  • 通过包装一个 FileReader 来读取 "note.txt" 文件,创建一个名为 brBufferedReader 实例。
  • 按行读取该文件。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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();
        }
    }
}
编辑并运行代码