Escribir y leer una nota
Ahora que ya puedes crear archivos, toca añadir contenido real. Vas a escribir una nota breve en un archivo de texto y luego la leerás para confirmar que se guardó correctamente. Esto es básico en cualquier aplicación de notas.
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
Instrucciones del ejercicio
- Escribe el texto
"Start from the beginning"en un archivo llamado"note.txt". - Crea un
FileWriteren modoappendpara"note.txt"llamadofwAppendMode. - Añade el texto
" Add to the end"al archivo sin sobrescribir su contenido. - Usa
FileReaderpara leer el contenido del archivo y muéstralo en la consola, carácter a carácter.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
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());
}
}
}