Menu
Coddy logo textTech

Write

Lección 5 de 11 del curso Manejo de archivos en Java de Coddy.

Para escribir en un archivo en Java, podemos usar la clase FileWriter:

try {
	FileWriter writer = new FileWriter("data.txt");
	writer.write("This the new contect of data.txt file!");
	writer.close();
} catch (IOException e) {
	System.out.println("An error occurred.");
	e.printStackTrace();
}

El código anterior escribe algo de texto en el archivo "data.txt", ten en cuenta que debes manejar la excepción IOException.

Por defecto, el texto sobrescribe cualquier texto existente; si deseas añadir el texto al contenido ya existente del archivo, utiliza esto:

 FileWriter writer = new FileWriter("data.txt", true);

Observa el true como el segundo argumento del constructor de FileWriter.

challenge icon

Desafío

Fácil

Se te proporciona el archivo llamado "coddy.txt" de antes. Añade al final de este archivo el siguiente texto:

This is the end of the file, but only the beginning...

Al final, imprime el nuevo contenido del archivo.

Pruébalo tú mismo

import java.io.FileWriter;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;

class Main {
    public static void main(String[] args) {
        // Escribe código aquí
    }
}

Todas las lecciones de Manejo de archivos en Java