Escritura en un fichero de texto
El siguiente código escribe un fichero de texto desde cero. Pone en él 10 líneas
import java.io.*;
public class EscribeFichero
{
public static void main(String[] args)
{
try
{
FileWriter fichero = new FileWriter("prueba.txt");
PrintWriter pw = new PrintWriter(fichero);
for (int i = 0; i < 10; i++)
pw.println("Linea " + i);
pw.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
Si queremos añadir al final de un fichero ya existente, simplemente debemos poner un flag a true como segundo parámetro del constructor de FileWriter.
FileWriter fichero = new FileWriter("prueba.txt",true);
execellent! I have to leave a piece of words here!