开始使用免费开始使用

写入并读取一条笔记

既然已经会创建文件,接下来就该写入真实内容了。您将把一条简短的笔记写入文本文件,然后再读回它,确认是否正确保存。这是任何笔记应用的核心功能。

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

本练习是课程的一部分

Java 中的输入/输出与流

查看课程

练习说明

  • 将文本 "Start from the beginning" 写入名为 "note.txt" 的文件。
  • "note.txt"append 模式创建一个 FileWriter,命名为 fwAppendMode
  • 在不覆盖已有内容的情况下,向文件追加文本 " Add to the end"
  • 使用 FileReader 读取文件内容,并在控制台逐字符显示。

交互式实操练习

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

class FileReadWrite {

    public static void main(String[] args) {
        try {
            FileWriter fw = new FileWriter("note.txt");
            // Write "Start from the beginning" to the file
            fw.____("Start from the beginning");
            fw.close();

            // Create a FileWriter in append mode
            FileWriter fwAppendMode = new ____("note.txt", ____);

            // Add " Add to the end" to the end of file
            fwAppendMode.____(" Add to the end");
            fwAppendMode.close();

            FileReader fr = new FileReader("note.txt");
            int character;
            
            // Read the file content character by character
            while ((character = fr.____()) != -1) {
                System.out.print((char) character);
            }
            fr.close();
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}
编辑并运行代码