How do I get PrintWriter to write a String variable in the .txt file?

0

My idea is to create a small .txt database to save a user's data.

public void menuContato(){
        try{
            FileWriter fw = new FileWriter("usuarios.txt");
            PrintWriter pw = new PrintWriter(fw);

        System.out.println("CRIAÇÃO DE CONTATO");

        System.out.println("Nome: ");
        this.nome = leitor.nextLine();
        pw.print(this.nome);

        System.out.println("Email: ");
        this.email = leitor.nextLine();
        pw.print(this.email);

        System.out.println("Telefone: ");
        this.telefone = leitor.nextLine();
        pw.print(this.telefone);

        Contato usuario = new Contato(nome, email,telefone);
        dados.registraContato(usuario);
         }

        catch(IOException e){
            out.println("ERRO");}


        }

The problem is that when I use pw.print () and put the variable, the file usuarios.txt is created, but nothing is written to the file.

What can I do?

    
asked by anonymous 16.01.2018 / 13:43

1 answer

1

You need to close pw, as this will cause it to actually write to the file. Notice that PrintWriter works with a stream of data which, in turn, is written to a file. Running the close () command indicates that the stream should be finalized and physically written to a file.

Add this to your code:

} finally {
  pw.close();
}
    
16.01.2018 / 13:49