Writing and Reading a Note
Now that you can create files, it's time to add real content. You'll write a short note to a text file and then read it back to confirm it was saved correctly. This is a core feature of any note-taking application.
Este exercício faz parte do curso
Input/Output and Streams in Java
Instruções do exercício
- Write the text "Start from the beginning"to a file named"note.txt".
- Create a FileWriterinappendmode for"note.txt"asfwAppendMode.
- Add the text " Add to the end"to the file without overwriting its content.
- Use FileReaderto read the content of the file and display it on the console, one character at a time.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
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());
        }
    }
}