How to get Printwriter to write in the file . txt determined String of a variable?

Asked

Viewed 141 times

0

My idea is to create a small database . txt 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 when I’m gonna use the Pw.print() and put the variable, the file users.txt is created, but nothing is written in the file.

What can I do?

1 answer

1


You need to close Pw, as this causes it to effectively write to the file. Note that Printwriter works with a data stream which, in turn, is written in a file. Executing the close() command indicates that the stream must be finished and physically written to a file.

Add that to your code:

} finally {
  pw.close();
}

Browser other questions tagged

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