Ajuda com arquivo texto { RESOLVIDO}

6 respostas
thaita

Pessoal,
Sou novato em java e recebi um programa exemplo pela internet de um amigo.Acontece que tentei rodar no neatbeans e apresentou vários erros na compilação.Podem me ajudar a resolver o problema?Segue o programa abaixo:

package AgendaC;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileWriter;

import java.util.Scanner;

/**

  • Exemplo de como fazer a leitura e a escrita em arquivos TXT com Java

  • Para a leitura é feito uso da classe Scanner

  • @author Enviado por um amigo
    */
    public class AgendaC {

    /* atributos */
    private String agenda;

    /* construtor */
     public AgendaC(String agenda) {
         this.agenda = agenda;
     }
    
     /* métodos */
     public void inserirDados(String registro) {
         File fArquivo = null;
         try {
             fArquivo = new File(this.agenda);
             FileWriter fwArquivo = null;
    
             // Verifica se o arquivo existe
             // Se existir, ele abre par adicionar dados
             // se nao existir, ele cria o arquivo
             if (fArquivo.exists() == true) {
                 fwArquivo = new FileWriter(fArquivo, true);
             } else {
                 fwArquivo = new FileWriter(fArquivo);
             }
    
             BufferedWriter bw = new BufferedWriter(fwArquivo);
    
             //escreve o registro no arquivo e pula uma linha com o \n
             bw.write(registro + "\n");
    
             System.out.println("Registro adicionado com sucesso...");
    
             //fecha o arquivo
             bw.close();
             fwArquivo.close();
    
         } catch (Exception e) {
             System.err.println("Erro ao inserir linhas no arquivo: " + fArquivo);
         }
     }
    
     public void listarDados() {
         Scanner lendoArquivo = null;
         File agenda = null;
         try {
             // abrindo o arquivo para leitura
             // se o arquivo nao existir será disparada uma exceção
             arquivo = new File(this.agenda);
             lendoArquivo = new Scanner(agenda);
    
             // leia o arquivo linha por linha até chegar ao seu fim
             while (lendoArquivo.hasNextLine()) {
                 this.processandoLinha(lendoArquivo.nextLine());
             }
    
    
         } catch (FileNotFoundException e) { // tratando quando o arquivo nao existe
             System.err.println("Erro: arquivo nao existe. " + agenda);
         } finally {
             // fechando o scanner
             try {
                 lendoArquivo.close();
             } catch (Exception e) {
             }
         }
     }
    
     private void processandoLinha(String linha) {
         // toda linha do arquivo segue o formato:
         // nome:telefone
         if (linha != null) {
             // separando os campos através do delimitador ':'
             String[] campos = linha.split(":");
    
             System.out.print("Nome: " + campos[0].trim());
                         System.out.print("E-mail: " + campos[1].trim());
    
          System.out.println("\tTelefone: " + campos[2].trim());
         System.out.println("--------------------------------------\n");
         }
     }
    
     public void menu() {
         // passando para o objeto da classe Scanner o dispositivo de entrada padrão
         // que é o teclado
         Scanner teclado = new Scanner(System.in);
         int op = 0;
         do {
             System.out.println("..:: Agenda de        Contabilistas ::..");
             System.out.println("1 - Inserir linha");
             System.out.println("2 - Listar todo arquivo");
             System.out.println("3 - Sair");
             System.out.print("Entre com uma opcao: ");
             op = teclado.nextInt();
    
             switch (op) {
                 case 1:
                     teclado.nextLine();
                     String nome;
                     String email;
                     
                   String telefone;
    
                     System.out.println("Entre com os dados:");
                     System.out.print("Nome: ");
                     nome = teclado.nextLine();
                    System.out.print("E-mail: ");
                 email = teclado.nextLine();
    
                     System.out.print("Telefone: ");
                 telefone = teclado.nextLine();
                     this.inserirDados(nome + ":" + telefone);
                     break;
                 case 2:
                     this.listarDados();
                     break;
                 default:
                     System.out.println("Opção inválida!");
             }
    
         } while (op != 3);
     }
    
     public static void main(String[] args) {
    
         AgendaC p = new AgendaC("ContabilistasN.txt");
    
         p.menu();
     }
    

    }

6 Respostas

magalli

Faz um Seguinte, Abre o netbeans vai em Arquivo -> Aplicação Java -> Próximo -> Nome do Projeto coloque Agenda -> Finalizar
ele vai criar o seguinte código dentro do pacote agenda na classe Agenda.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package agenda;

/**
 *
 * @author 
 */
public class Agenda {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }
}

Então você apaga tudo e coloca isso

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package agenda;


import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileWriter; 
import java.util.Scanner; 

/** 
* Exemplo de como fazer a leitura e a escrita em arquivos TXT com Java 
* Para a leitura é feito uso da classe Scanner 
* 
* @author Enviado por um amigo 
*/ 
public class Agenda { 

/* atributos */ 
private String agenda; 

/* construtor */ 
public Agenda(String agenda) { 
this.agenda = agenda; 
} 

/* métodos */ 
public void inserirDados(String registro) { 
File fArquivo = null; 
try { 
fArquivo = new File(this.agenda); 
FileWriter fwArquivo = null; 

// Verifica se o arquivo existe 
// Se existir, ele abre par adicionar dados 
// se nao existir, ele cria o arquivo 
if (fArquivo.exists() == true) { 
fwArquivo = new FileWriter(fArquivo, true); 
} else { 
fwArquivo = new FileWriter(fArquivo); 
} 

BufferedWriter bw = new BufferedWriter(fwArquivo); 

//escreve o registro no arquivo e pula uma linha com o \n 
bw.write(registro + "\n"); 

System.out.println("Registro adicionado com sucesso..."); 

//fecha o arquivo 
bw.close(); 
fwArquivo.close(); 

} catch (Exception e) { 
System.err.println("Erro ao inserir linhas no arquivo: " + fArquivo); 
} 
} 

public void listarDados() { 
Scanner lendoArquivo = null; 
File agenda = null; 
try { 
// abrindo o arquivo para leitura 
// se o arquivo nao existir será disparada uma exceção 
arquivo = new File(this.agenda); 
lendoArquivo = new Scanner(agenda); 

// leia o arquivo linha por linha até chegar ao seu fim 
while (lendoArquivo.hasNextLine()) { 
this.processandoLinha(lendoArquivo.nextLine()); 
} 


} catch (FileNotFoundException e) { // tratando quando o arquivo nao existe 
System.err.println("Erro: arquivo nao existe. " + agenda); 
} finally { 
// fechando o scanner 
try { 
lendoArquivo.close(); 
} catch (Exception e) { 
} 
} 
} 

private void processandoLinha(String linha) { 
// toda linha do arquivo segue o formato: 
// nome:telefone 
if (linha != null) { 
// separando os campos através do delimitador ':' 
String[] campos = linha.split(":"); 

System.out.print("Nome: " + campos[0].trim()); 
System.out.print("E-mail: " + campos[1].trim()); 

System.out.println("\tTelefone: " + campos[2].trim()); 
System.out.println("--------------------------------------\n"); 
} 
} 

public void menu() { 
// passando para o objeto da classe Scanner o dispositivo de entrada padrão 
// que é o teclado 
Scanner teclado = new Scanner(System.in); 
int op = 0; 
do { 
System.out.println("..:: Agenda de Contabilistas ::.."); 
System.out.println("1 - Inserir linha"); 
System.out.println("2 - Listar todo arquivo"); 
System.out.println("3 - Sair"); 
System.out.print("Entre com uma opcao: "); 
op = teclado.nextInt(); 

switch (op) { 
case 1: 
teclado.nextLine(); 
String nome; 
String email; 

String telefone; 

System.out.println("Entre com os dados:"); 
System.out.print("Nome: "); 
nome = teclado.nextLine(); 
System.out.print("E-mail: "); 
email = teclado.nextLine(); 

System.out.print("Telefone: "); 
telefone = teclado.nextLine(); 
this.inserirDados(nome + ":" + telefone); 
break; 
case 2: 
this.listarDados(); 
break; 
default: 
System.out.println("Opção inválida!"); 
} 

} while (op != 3); 
} 

public static void main(String[] args) { 

Agenda p = new Agenda("ContabilistasN.txt"); 

p.menu(); 
} 
}

ele tem que retonar isto para você

run:
..:: Agenda de Contabilistas ::..
1 - Inserir linha
2 - Listar todo arquivo
3 - Sair
Entre com uma opcao:
thaita

Ok. Procedi como vc disse e depois executei e apresenta um erro na linha 68 : "Cannot find symbol: Variable arquivo location : class:agenda. Como proceder???

A

Oi thaita, acredito que fique assim:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

    
import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileWriter; 
import java.util.Scanner; 

/** 
 * Exemplo de como fazer a leitura e a escrita em arquivos TXT com Java 
 * Para a leitura é feito uso da classe Scanner 
 * 
 * @author Enviado por um amigo 
 */ 
public class Agenda { 

    /* atributos */ 
    private String agenda; 

    /* construtor */ 
    public Agenda(String agenda) { 
        this.agenda = agenda; 
    } 

    /* métodos */ 
    public void inserirDados(String registro) { 
        File fArquivo = null; 
        try { 
            fArquivo = new File(this.agenda); 
            FileWriter fwArquivo = null; 

            // Verifica se o arquivo existe 
            // Se existir, ele abre par adicionar dados 
            // se nao existir, ele cria o arquivo 
            if (fArquivo.exists() == true) { 
                fwArquivo = new FileWriter(fArquivo, true); 
            } else { 
                fwArquivo = new FileWriter(fArquivo); 
            } 

            BufferedWriter bw = new BufferedWriter(fwArquivo); 

            //escreve o registro no arquivo e pula uma linha com o \n 
            bw.write(registro + "\n"); 

            System.out.println("Registro adicionado com sucesso..."); 

            //fecha o arquivo 
            bw.close(); 
            fwArquivo.close(); 

        } catch (Exception e) { 
            System.err.println("Erro ao inserir linhas no arquivo: " + fArquivo); 
        } 
    } 

    public void listarDados() { 
        Scanner lendoArquivo = null; 
        File arquivo = null; 
        try { 
            // abrindo o arquivo para leitura 
            // se o arquivo nao existir será disparada uma exceção 
            arquivo = new File(this.agenda); 
            lendoArquivo = new Scanner(arquivo); 

            // leia o arquivo linha por linha até chegar ao seu fim 
            while (lendoArquivo.hasNextLine()) { 
                this.processandoLinha(lendoArquivo.nextLine()); 
            } 

        } catch (Exception e) { // tratando quando o arquivo nao existe 
            System.err.println("Erro: arquivo nao existe. " + agenda); 
        } finally { 
            // fechando o scanner 
            try { 
                lendoArquivo.close(); 
            } catch (Exception e) { 
            } 
        } 
    } 

    private void processandoLinha(String linha) { 
        // toda linha do arquivo segue o formato: 
        // nome:telefone 
        if (linha != null) { 
            // separando os campos através do delimitador ':' 
            String[] campos = linha.split(":"); 

            System.out.print("Nome: " + campos[0].trim()); 
            System.out.print("E-mail: " + campos[1].trim()); 

            System.out.println("\tTelefone: " + campos[2].trim()); 
            System.out.println("--------------------------------------\n"); 
        } 
    } 

    public void menu() { 
        // passando para o objeto da classe Scanner o dispositivo de entrada padrão 
        // que é o teclado 
        Scanner teclado = new Scanner(System.in); 
        int op = 0; 
        do { 
            System.out.println("..:: Agenda de Contabilistas ::.."); 
            System.out.println("1 - Inserir linha"); 
            System.out.println("2 - Listar todo arquivo"); 
            System.out.println("3 - Sair"); 
            System.out.print("Entre com uma opcao: "); 
            op = teclado.nextInt(); 

            switch (op) { 
                case 1: 
                teclado.nextLine(); 
                String nome; 
                String email; 

                String telefone; 

                System.out.println("Entre com os dados:"); 
                System.out.print("Nome: "); 
                nome = teclado.nextLine(); 
                System.out.print("E-mail: "); 
                email = teclado.nextLine(); 

                System.out.print("Telefone: "); 
                telefone = teclado.nextLine(); 
                this.inserirDados(nome + ":" + telefone); 
                break; 
                case 2: 
                this.listarDados(); 
                break; 
                default: 
                System.out.println("Opção inválida!"); 
            } 

        } while (op != 3); 
    } 

    public static void main(String[] args) { 

        Agenda p = new Agenda("ContabilistasN.txt"); 

        p.menu(); 
    } 
}

alterei o apenas metodo listarDados.

thaita

Prezado Antonio.
agradeço a ajuda prestada. Tudo esta correto agora e pude analisar todas as funções. Somente uma dúvida ainda persiste: Inseri 05 registros no arquivo texto e quando mandei listar , só apareceu o primeiro registro. Pode me explicar porque isso esta ocorrendo?

A

thaita, não estava gravando nem buscando as informações corretamente porque quando você fazia o split dos dados um campo não estava sendo passado que era o e-mail, e isto acabava gerando uma exception de indexOutOfBound,

corrigi a parte que estava passando só o nome e o telefone da pessoa, agora está passando nome, email e telefone.
Agora busca e insere linhas no seu arquivo .txt, com no formato “nome:email:telefone”.
Veja se está correto, segue abaixo o codigo modificado:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

    
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

/** 
 * Exemplo de como fazer a leitura e a escrita em arquivos TXT com Java 
 * Para a leitura é feito uso da classe Scanner 
 * 
 * @author Enviado por um amigo 
 */ 
public class Agenda { 

    /* atributos */ 
    private String agenda;
	private Scanner teclado; 

    /* construtor */ 
    public Agenda(String agenda) { 
        this.agenda = agenda; 
    } 

    /* métodos */ 
    public void inserirDados(String registro) { 
        File fArquivo = null; 
        try { 
            fArquivo = new File(this.agenda); 
            FileWriter fwArquivo = null; 

            // Verifica se o arquivo existe 
            // Se existir, ele abre par adicionar dados 
            // se nao existir, ele cria o arquivo 
            if (fArquivo.exists() == true) { 
                fwArquivo = new FileWriter(fArquivo, true); 
            } else { 
                fwArquivo = new FileWriter(fArquivo); 
            } 

            BufferedWriter bw = new BufferedWriter(fwArquivo); 

            //escreve o registro no arquivo e pula uma linha com o \n 
            bw.write(registro);
            bw.newLine();

            System.out.println("Registro adicionado com sucesso..."); 

            //fecha o arquivo 
            bw.close(); 
            fwArquivo.close(); 

        } catch (Exception e) { 
            System.err.println("Erro ao inserir linhas no arquivo: " + fArquivo); 
        } 
    } 

    public void listarDados() { 
        Scanner lendoArquivo = null; 
        File arquivo = null; 
        try { 
            // abrindo o arquivo para leitura 
            // se o arquivo nao existir será disparada uma exceção 
            arquivo = new File(this.agenda); 
            lendoArquivo = new Scanner(arquivo); 

            // leia o arquivo linha por linha até chegar ao seu fim 
            while (lendoArquivo.hasNextLine()) { 
                this.processandoLinha(lendoArquivo.nextLine()); 
            } 

        } catch (Exception e) { // tratando quando o arquivo nao existe 
            System.err.println("Erro: arquivo nao existe. " + agenda); 
        } finally { 
            // fechando o scanner 
            try { 
                lendoArquivo.close(); 
            } catch (Exception e) { 
            } 
        } 
    } 

    private void processandoLinha(String linha) { 
        // toda linha do arquivo segue o formato: 
        // nome:telefone 

    	if (linha != null) { 
            // separando os campos através do delimitador ':' 
            String[] campos = linha.split(":"); 
            if(campos.length>0){
            	System.out.println("Nome: " + campos[0].trim());
            }
            if(campos.length>1){
            	System.out.println("E-mail: " + campos[1].trim());
            }
            if(campos.length>2){
            	System.out.println("Telefone: " + campos[2].trim());
            }
            System.out.println("--------------------------------------\n"); 
        } 
    } 

    public void menu() { 
        teclado = new Scanner(System.in); 
        int op = 0; 
        do { 
            System.out.println("..:: Agenda de Contabilistas ::.."); 
            System.out.println("1 - Inserir linha"); 
            System.out.println("2 - Listar todo arquivo"); 
            System.out.println("3 - Sair"); 
            System.out.print("Entre com uma opcao: "); 
            op = teclado.nextInt(); 

            switch (op) { 
                case 1: 
                teclado.nextLine(); 
                String nome; 
                String email; 

                String telefone; 

                System.out.println("Entre com os dados:"); 
                System.out.print("Nome: "); 
                nome = teclado.nextLine(); 
                System.out.print("E-mail: "); 
                email = teclado.nextLine(); 

                System.out.print("Telefone: "); 
                telefone = teclado.nextLine(); 
                this.inserirDados(nome + ":" + email + ":" + telefone); 
                break; 
                case 2: 
                this.listarDados(); 
                break; 
                default: 
                System.out.println("Opção inválida!"); 
            } 

        } while (op != 3); 
    } 

    public static void main(String[] args) { 

        Agenda p = new Agenda("ContabilistasN.txt"); 

        p.menu(); 
    } 
}
thaita

Valeu Antonio. Muito obrigado. Um grande abraço.

Criado 30 de janeiro de 2013
Ultima resposta 31 de jan. de 2013
Respostas 6
Participantes 3