Append lines to existing file

1

I'm trying to append lines to a report, but new lines are overwriting old ones.

Class with method main:

import java.io.FileNotFoundException;

public class TesteInscricoes {

    public static void main(String[] args) throws FileNotFoundException {


        Equipante gabriel = new Equipante();
        gabriel.setNome("Gabriel");
        Equipante milena = new Equipante();
        milena.setNome("Milena");

        InscricaoDeEquipante inscricaoDeEquipante = new InscricaoDeEquipante();
        inscricaoDeEquipante.inscreveEquipantes(gabriel);
        inscricaoDeEquipante.inscreveEquipantes(milena);
    }
}

Enrollment class:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

public class InscricaoDeEquipante {

    public void inscreveEquipantes(Equipante equipante) throws FileNotFoundException {

        PrintWriter inscreve = new PrintWriter(new FileOutputStream(new File("Inscricoes.csv")), true);     
        inscreve.append(equipante.getNome());

        inscreve.close();
    }
}

At the end, the file only has the name "Milena".

I'm starting with java and I'm having difficulties with IO.

What do I need to use to get the expected result ??

    
asked by anonymous 19.07.2018 / 04:08

1 answer

1

The constructor used is FileOutputStream(File) with only one parameter. This will always create a new file. To add to the end of the file use the FileOutputStream(File, boolean) constructor passing true as the second parameter. Documentation :

  

... If the second argument is true, then it will be written to the end of the file rather than the beginning. ...

Example:

... new PrintWriter(new FileOutputStream(new File("Inscricoes.csv"), true), true);

(Was the problem just a ) in the wrong position?)

Note : Could use the FileOutputStream(String, boolean) constructor without having to create an instance of File .

Note 2 : it does not do much to use a PrintWriter in this current code; but I do not know if you want to add more data to the file (separating the data because it is a CSV)

Example with FileWriter :

Writer inscreve = new FileWriter("Inscricoes.csv", true);

(not tested, based solely on documentation)     

19.07.2018 / 09:32