To avoid overwriting the file, use the class FileWritter and enable the option append (add).
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); //opción append habilitada!
FileWriter (String fileName, boolean append) :
Parameters:
fileName - String with the file name dependent on the system.
Append - boolean if true
, then the data will be written to the end of the file instead of the beginning.
This is an example in which if the file does not exist for the first time, it creates it and then adds the text to the content.
BufferedWriter bw = null;
FileWriter fw = null;
try {
String data = "Hola stackoverflow.com...";
File file = new File("archivo.txt");
// Si el archivo no existe, se crea!
if (!file.exists()) {
file.createNewFile();
}
// flag true, indica adjuntar información al archivo.
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(data);
System.out.println("información agregada!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//Cierra instancias de FileWriter y BufferedWriter
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
The result would be a file with name file.txt which will not overwrite the text but will add it to the contents of the file, something similar to:
Hola stackoverflow.com...Hola stackoverflow.com...Hola stackoverflow.com...Hola stackoverflow.com...Hola stackoverflow.com...