Handling Long Notes Efficiently
As users write longer notes, performance becomes important. Java's buffered classes help read and write large chunks of text efficiently. In this exercise, you'll use BufferedReader and BufferedWriter to handle a note saved in "note.txt".
Este exercício faz parte do curso
Input/Output and Streams in Java
Instruções do exercício
- Create an instance of BufferedWritercalledbwby wrapping aFileWriterfor the file named"note.txt".
- Write the first line of text, "This is the first line", to the file. Then add a line break using the.newLine()method and write the second line of text,"This is the second line", to the file.
- Create an instance of BufferedReadercalledbrby wrapping aFileReaderto read the file"note.txt".
- Read the file line by line.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
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();
        }
    }
}