Append lines in an existing file

Asked

Viewed 39 times

1

I’m trying to add lines to a report, but the new lines are overwriting the old ones.

Class with main method:

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);
    }
}

Class making the inscription:

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 presents only the name "Milena".

I’m starting with java and I’m struggling with IO.

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

1 answer

1


The builder 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 constructor FileOutputStream(File, boolean) passing by true as the second parameter. Documentation:

... If the Second argument is true, then bytes will be Written to the end of the file rather than the Beginning. ...

Example:

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

(the problem was only one ) in the wrong position?)

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

Note 2: doesn’t make you feel much like using a PrintWriter in this current code; but I do not know if you want to add more data to the file (separation between the data because it is a CSV)

Example with FileWriter:

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

(untested, based solely on documentation)

  • In fact, I see that I missed the constructor where I put the parameter true. Regarding the second note, I chose Printwriter because I find it easier, but in this case what is recommended to use??

Browser other questions tagged

You are not signed in. Login or sign up in order to post.