1
Good morning, I’m having a question, I have this code, which is a contact book and the data should be persisted in a txt file. What happens is that the program runs normally, but the data is not saved in that file, which I stored in a folder located on disk c, Someone could give me a light?
package agenda.estruturada;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
/**
 *
 * @author Yure
 */
public class AgendaEstruturada {
/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException {
    //Instanciando a classe ArrayList para uso
    ArrayList<String>agenda = new ArrayList<String>();
    //Instanciando a Classe Scanner
    Scanner ler = new Scanner(System.in);
    //Opção que será passada pelo usuário na escolha do menu
    int opcao;
            importar(agenda);//importando os dados
    do{
        System.out.println("***** Menu Principal *****");
        System.out.println("[1] Incluir Contato");
        System.out.println("[2] Excluir Contato");
        System.out.println("[3] Listar Contatos");
        System.out.println("[4] Pesquisar Contatos");
        System.out.println("[0] Encerrar Programa\n");
        opcao = ler.nextInt();
            switch(opcao){
                    case 1:incluir(agenda);break;
                    case 2:excluir(agenda);break;
                    case 3:listar(agenda);break;
                    case 4:pesquisar(agenda);break;
        }
        System.out.println("\n");
    }while(opcao!=0);
            exportar(agenda);//Exportando os dados
    }
               /**Método que irá importar os dados para Lista*/
                public static void importar(ArrayList<String>agenda){
                        try{
                            FileReader arq = new FileReader("C:\\Agenda\\agenda.txt");
                            BufferedReader lerArq = new BufferedReader(arq);
                            String linha = lerArq.readLine();//lê a primeira linha
                            // a variável "linha" recebe o valor "null" quando o processo 
                            // de repetição atingir o final do arquivo texto
                                while(linha!=null){
                                    agenda.add(linha);
                                    linha = lerArq.readLine();// lê da segunda até a última linha
                                }
                                arq.close();
                        }catch(IOException err){
                              System.err.printf("Erro na cobertura do arquivo %s.",err.getMessage());                       
                        }
                }
                /**Método para buscar os dados da lista*/
                public static void exportar(ArrayList<String>agenda) throws IOException{
                    FileWriter arq = new FileWriter("C:\\Agenda\\agenda.txt");
                    PrintWriter gravarArq = new PrintWriter(arq);
                    int i;
                    int n = agenda.size();
                            for(i=0;i<n;i++){
                                gravarArq.printf("%s%n"+ agenda.get(i));
                            }
                gravarArq.close();
                }
                    public static void incluir(ArrayList<String>agenda){
                        Scanner ler = new Scanner(System.in);
                        String nome, telefone;
                        System.out.printf("|informe o nome do contato\n");
                        nome = ler.nextLine();
                        System.out.printf("|informe o telefone do contato\n");
                        telefone = ler.nextLine();
                        //Grava os dados no fim da lista
                        agenda.add(nome + ":" + telefone);   
                    }
                    public static void excluir(ArrayList<String>agenda){
                        Scanner ler = new Scanner(System.in);
                        int i;
                        listar(agenda);
                        System.out.printf("\nInforme o indice da posição a ser excluida\n");
                        i = ler.nextInt();
                        try{
                           agenda.remove(i);
                        }catch(IndexOutOfBoundsException err){
                        // exceção lançada para indicar que um índice (i) 
                        // está fora do intervalo válido (de 0 até agenda.size()-1)
                            System.out.printf("\nErro: Posição inválida(%s).\n\n", err.getMessage());
                        }
                    }
                    public static void listar(ArrayList<String>agenda){
                        System.out.printf("\nListando os itens da agenda\n");
                        int i, n = agenda.size();
                        for (i=0;i<n;i++){
                            System.out.printf("Posição %d- %s\n",i,agenda.get(i));
                        }
                        System.out.printf("--------------------------------------------------");
                    }
                    public static void pesquisar(ArrayList<String>agenda){
                        Scanner ler = new Scanner(System.in);
                        String s;
                        System.out.printf("\nInforme o nome do contato\n");
                        s = ler.nextLine();
                        s = s.toUpperCase();
                        String dados[];
                        int i, n = agenda.size();
                            for(i = 0;i<n;i++){
                                // informando "joão", por exemplo, na entrada serão mostrados 
                                // todos os contatos que possuem "joão" no nome
                                if(agenda.get(i).toUpperCase().indexOf(s)!=-1){
                                  dados = agenda.get(i).split(":");
                                    System.out.printf("\nNome....:%s\n",dados[0]);
                                    System.out.printf("\nTelefone:%s\n",dados[1]);
                                }
                            }
                    }
}
In the builder of
Filewriter, you need to inform a true so that the content is appended to the existing content.– user28595
Strip that
throwsof the main method and makes thetry/catch– DiegoAugusto
It didn’t work, I put true in the Filewriter constructor and replaced throws with Try/catch, but it doesn’t persist yet.
– Yure Santana
It is not to persist, if you do the
try/catchyou can capture possible exceptions.e.printStackTrace();– DiegoAugusto