Dúvida - Trabalhando com manupulação de arquivos

3 respostas
ricardoschet

Estou fazendo um programinha de cadastros que grava os dados em arquivos .txt
Tenho a opção de alterar um dado cadastrado, porém após escolher o dado a ser alterado ele seta os outros campos como null, gostaria, se possível que dessem uma olhada no código, o erro deve ser besta :)

package tentar;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JOptionPane;

public class Main {

    public static void main(String[] args) {
        Object[] especialidadeJuridica = {"Civil", "Criminal", "Trabalhista"};

        File pasta = new File("C:/Programa");
        pasta.mkdir();

        int option = 0;
        do {
            String entrada = JOptionPane.showInputDialog("Escolha uma opção:"
                    + "\n1) Visualizar dados cadastrados"
                    + "\n2) Adicionar novo cadastro"
                    + "\n3) Alterar cadastro"
                    + "\n4) Deletar cadastro"
                    + "\n5) Fechar o programa.");
            try {
                option = Integer.parseInt(entrada);
                if (option == 1) {
                    showItems();
                } else if (option == 2) {
                    String name = JOptionPane.showInputDialog("Entre com o nome da pessoa");
                    Object especial = JOptionPane.showInputDialog(null, "Escolha:", "Especialidade Jurídica", JOptionPane.PLAIN_MESSAGE, null, especialidadeJuridica, "");
                    String housePhone = JOptionPane.showInputDialog("Entre com o telefone Residencial");
                    String comercialPhone = JOptionPane.showInputDialog("Entre com o telefone comercial");
                    String streetAdress = JOptionPane.showInputDialog("Entre com o endereço");
                    String OAB_code = JOptionPane.showInputDialog("Entre com o código OAB");
                    addItem(name, (String) especial, housePhone, comercialPhone, streetAdress, OAB_code);
                } else if (option == 3) {
                    try {
                        String inputCode = JOptionPane.showInputDialog("Entre com o código do item:");
                        int code = Integer.parseInt(inputCode);

                        int setOption = Integer.parseInt(JOptionPane.showInputDialog("O que deseja alterar?\n1-Nome\n2-Especialidade Jurídica\n3-Telefone Residencial\n4-Telefone Comercial\n5-Endereço\n6-Código OAB"));
                        if (setOption==1){
                        String newName = JOptionPane.showInputDialog("Entre com o nome alterado");
                        setName(code,newName);
                        }
                        if (setOption==2){
                        Object newEspecial = JOptionPane.showInputDialog(null, "Escolha:", "Especialidade Jurídica", JOptionPane.PLAIN_MESSAGE, null, especialidadeJuridica, "");
                        setEspecial(code,(String)newEspecial);
                        }
                        if (setOption==3){
                         String newhousePhone = JOptionPane.showInputDialog("Entre com o novo telefone residencial");
                         sethousePhone(code,newhousePhone);
                        }
                        if (setOption==4){
                             String newcomercialPhone = JOptionPane.showInputDialog("Entre com o novo telefone comercial");
                             setcomercialPhone(code,newcomercialPhone);
                        }
                        if (setOption==5){
                             String newstreetAdress = JOptionPane.showInputDialog("Entre com o novo endereço");
                             setStreet(code,newstreetAdress);
                        }
                        if (setOption==6){
                            String newOAB = JOptionPane.showInputDialog("Entre com o novo código OAB");
                            setOAB(code,newOAB);
                        }
                        /*
                       
                        
                       
                       
                        
                        setItem(code, newName, (String) newEspecial, newhousePhone, newcomercialPhone, newstreetAdress, newOAB);*/
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "Cadastro não encontrado");
                    }
                } else if (option == 4) {
                    try {
                        String inputCode = JOptionPane.showInputDialog("Entre com o código do item:");
                        int code = Integer.parseInt(inputCode);
                        deleteItem(code);
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "Cadastro não encontrado");
                    }
                } else if (option != 5) {
                    JOptionPane.showMessageDialog(null, "Opção inválida");
                }
            } catch (Exception ex) {
                option = 0;
                JOptionPane.showMessageDialog(null, "Opção inválida");
            }
        } while (option != 5);
    }

    static void showItems() throws IOException {
        File pasta = new File("C:/Programa");
        String files[] = pasta.list();
        for (String file : files) {
            System.out.print(file);
            BufferedReader item = null;
            try {
                item = new BufferedReader(new FileReader("C:/Programa/" + file));
                String name = item.readLine();
                String especial = item.readLine();
                String housePhone = item.readLine();
                String comercialPhone = item.readLine();
                String streetAdress = item.readLine();
                String OAB_code = item.readLine();
                System.out.print("\nNOME:" + name + "\nESPECIALIDADE JURÍDICA: " + especial + "\nTELEFONE RESIDENCIAL: " + housePhone
                        + "\nTELEFONE COMERCIAL: " + comercialPhone + "\nENDEREÇO: " + streetAdress + "\nCÓDIGO OAB: " + OAB_code + "\n--------------------------------");

            } catch (Exception ex) {
                System.out.print("\t\tErro! Tente novamente" + ex.getMessage());
            } finally {
                if (item != null) {
                    item.close();
                }
            }
            System.out.println("");
        }
        if (files.length >= 2) {
            System.out.println("Seu programa possui " + files.length + " cadastros."); /* Mensagem personalizada para qtde de cadastros*/
        }
        if (files.length == 1) {
            System.out.println("Seu programa possui " + files.length + " cadastro.");
        }
        if (files.length == 0) {
            System.out.println("Seu programa não possui nenhum dado cadastrado!");
        }
    }

    static void addItem(String name, String especial, String housePhone, String comercialPhone,
            String streetAdress, String OAB_code) {
        PrintWriter file = null;
        try {
            int code = new File("C:/Programa").list().length + 1;
            file = new PrintWriter("C:/Programa/" + code + ".txt");
            file.println(name);
            file.println(especial);
            file.println(housePhone);
            file.println(comercialPhone);
            file.println(streetAdress);
            file.println(OAB_code);
            JOptionPane.showMessageDialog(null, "Cadastro efetuado com sucesso!");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao inserir um item: \n\n" + ex.getMessage());
        } finally {
            if (file != null) {
                file.close();
            }
        }
    }

    static void setItem(int code, String newName, String newEspecial, String newhousePhone,
            String newcomercialPhone, String newstreetAdress, String newOAB) {
        PrintWriter file = null;
        try {
            file = new PrintWriter("C:/Programa/" + code + ".txt");
            file.println(newName);
            file.println(newEspecial);
            file.println(newhousePhone);
            file.println(newcomercialPhone);
            file.println(newstreetAdress);
            file.println(newOAB);
            JOptionPane.showMessageDialog(null, "Cadastro alterado com sucesso!");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Erro ao alterar cadastro: \n\n" + ex.getMessage());
        } finally {
            if (file != null) {
                file.close();
            }
        }
    }

    static void setOAB(int code,String newOAB){
        PrintWriter file = null;
        try{
            file= new PrintWriter("C:/Programa/" + code + ".txt");
            file.println(newOAB);
            JOptionPane.showMessageDialog(null, "Cadastro alterado com sucesso!");
        } catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Erro ao alterar cadastro: \n\n" + ex.getMessage());
        } finally{
                if (file!=null){
                    file.close();
                }
    }
    }
     static void setStreet(int code,String newstreetAdress){
        PrintWriter file = null;
        try{
            file= new PrintWriter("C:/Programa/" + code + ".txt");
            file.println(newstreetAdress);
            JOptionPane.showMessageDialog(null, "Cadastro alterado com sucesso!");
        } catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Erro ao alterar cadastro: \n\n" + ex.getMessage());
        } finally{
                if (file!=null){
                    file.close();
                }
    }
    }
      static void setcomercialPhone(int code,String newcomercialPhone){
        PrintWriter file = null;
        try{
            file= new PrintWriter("C:/Programa/" + code + ".txt");
            file.println(newcomercialPhone);
            JOptionPane.showMessageDialog(null, "Cadastro alterado com sucesso!");
        } catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Erro ao alterar cadastro: \n\n" + ex.getMessage());
        } finally{
                if (file!=null){
                    file.close();
                }
    }
    }
       static void sethousePhone(int code,String newhousePhone){
        PrintWriter file = null;
        try{
            file= new PrintWriter("C:/Programa/" + code + ".txt");
            file.println(newhousePhone);
            JOptionPane.showMessageDialog(null, "Cadastro alterado com sucesso!");
        } catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Erro ao alterar cadastro: \n\n" + ex.getMessage());
        } finally{
                if (file!=null){
                    file.close();
                }
    }
    }
        static void setEspecial(int code,String newEspecial){
        PrintWriter file = null;
        try{
            file= new PrintWriter("C:/Programa/" + code + ".txt");
            file.println(newEspecial);
            JOptionPane.showMessageDialog(null, "Cadastro alterado com sucesso!");
        } catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Erro ao alterar cadastro: \n\n" + ex.getMessage());
        } finally{
                if (file!=null){
                    file.close();
                }
    }
    }
         static void setName(int code,String newName){
        PrintWriter file = null;
        try{
            file= new PrintWriter("C:/Programa/" + code + ".txt");
            file.println(newName);
            JOptionPane.showMessageDialog(null, "Cadastro alterado com sucesso!");
        } catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Erro ao alterar cadastro: \n\n" + ex.getMessage());
        } finally{
                if (file!=null){
                    file.close();
                }
    }
    }

    static void deleteItem(int code) {
        File file = new File("C:/Programa/" + code + ".txt");
        if (file.exists()) {
            JOptionPane.showMessageDialog(null, "Cadastro excluido com sucesso!");
            if (file.delete() == false) {
                JOptionPane.showMessageDialog(null, "Erro ao excluir o cadastro " + code);
            }
        } else {
            JOptionPane.showMessageDialog(null, "O cadastro " + code + " não foi localizado");
        }
    }
}

3 Respostas

mauricioadl

isso acontece porque quando a pessoa faz a alteração ela altera somente um campo, e os outros ficam como null, dae quando voce chama a funcao que altera no arquivo os campos estao null porque a pessoa digitou somente o que ela quis alterar. entendeu?

ricardoschet

Ok, mas como faço para manter os demais campos intactos, alterando apenas o campo desejado e mantendo os outros com os dados correspondentes?

mauricioadl

vc deve carregar os dados do arquivo alterar somente o dado que voce quer e depois salvar.

Criado 16 de dezembro de 2011
Ultima resposta 16 de dez. de 2011
Respostas 3
Participantes 2