ComenzarEmpieza gratis

Gestionar notas largas de forma eficiente

A medida que los usuarios escriben notas más largas, el rendimiento se vuelve esencial. Las clases con búfer de Java facilitan la lectura y escritura eficiente de grandes bloques de texto. En este ejercicio, usarás BufferedReader y BufferedWriter para trabajar con una nota guardada en "note.txt".

Todos los paquetes necesarios de java.io ya se han importado por ti.

Este ejercicio forma parte del curso

Entrada/Salida y Streams en Java

Ver curso

Instrucciones del ejercicio

  • Crea una instancia de BufferedWriter llamada bw encapsulando un FileWriter para el archivo "note.txt".
  • Escribe la primera línea de texto, "This is the first line", en el archivo. Luego añade un salto de línea con el método .newLine() y escribe la segunda línea de texto, "This is the second line".
  • Crea una instancia de BufferedReader llamada br encapsulando un FileReader para leer el archivo "note.txt".
  • Lee el archivo línea a línea.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

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();
        }
    }
}
Editar y ejecutar código