Results 1 to 8 of 8
  1. #1
    JeremyLin is offline Member
    Join Date
    Feb 2012
    Posts
    11
    Rep Power
    0

    Default Reading / Writing to a binary file

    Hello everyone.
    I'm almost finished with my project but I'm having a few problems with my methods for writing and reading to / from a binary file.

    These are my methods for reading / writing I have on my main class :

    Writing :

    Java Code:
    public static void imprimeclientes () {
                Clientes c = new Clientes();
                System.out.println(c.toString());
                try{
                c.gravaBin("clientes.dat");
                }
                catch (IOException e) {System.out.println("Erro!!");}
           }
    Reading :
    Java Code:
    public static void leclientes () {
    Clientes c = new Clientes();
    try{
                    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("clientes.dat"));
                    c = (Clientes)ois.readObject();
       }
                catch (IOException e) {System.out.println("Erro!!");}
                catch (ClassNotFoundException e) {System.out.println("Falta a classe!");}
            }
    These are my methods I call on my Clientes class :

    Writing

    Java Code:
    public void gravaBin (String nomeFicheiro) throws IOException {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(nomeFicheiro));
            
            oos.writeObject(this);
            oos.flush();
            oos.close();
        }
    Any idea why it's not working properly ?

    Thanks.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  3. #3
    JeremyLin is offline Member
    Join Date
    Feb 2012
    Posts
    11
    Rep Power
    0

    Default Re: Reading / Writing to a binary file

    When I select on my main the option to save the clients, it creates the "clientes.dat" and writes inside it this :

    "¬í¬í¬í¬í¬í¬NUL¬í¬í¬í¬í¬íHashSet¬í¬í¬í¬í¬í¬í¬í ¬í"

    These type of symbols.

    Then I delete the cliente and when I read from the file, it loads no clients.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Reading / Writing to a binary file

    Quote Originally Posted by JeremyLin View Post
    When I select on my main the option to save the clients, it creates the "clientes.dat" and writes inside it this :

    "¬í¬í¬í¬í¬í¬NUL¬í¬í¬í¬í¬íHashSet¬í¬í¬í¬í¬í¬í¬í ¬í"

    These type of symbols.
    You're writing binary data to a file, not text, and so you shouldn't expect the data in the file to be readable as text.

    Then I delete the cliente and when I read from the file, it loads no clients.
    Your code above does appear to create a single empty Clientes object and appears to serialize it, but it doesn't appear to be able to store any useful information. I assume that your program already has one or more Clientes objects when this method is called, and that perhaps your goal is to serialize this object or these objects (you may want to fill us in on the details), but if so, again I don't see how your code will do it.

    For one, you don't want to create a new Clientes object within the methods above but rather use the ones you have. Perhaps the method to write should take a Clientes parameter?

    I could be wrong as I have no knowledge about what the rest of your code, including your Clientes class is doing. Again, you will need to take some time to provde the details necessary for us to answer this.

  5. #5
    JeremyLin is offline Member
    Join Date
    Feb 2012
    Posts
    11
    Rep Power
    0

    Default Re: Reading / Writing to a binary file

    I'll post both Clientes and Cliente class's code.

    Clientes :

    Java Code:
    import java.io.*;
    import java.util.*;
    public class Clientes implements Serializable
    {
     Set<Cliente> clients;//Tree
     
        //Construtor vazio
        public Clientes(){
            this.clients=new HashSet<Cliente>();//new ComparadorContrato()
    
        }
        
        
        
        public void mudanome(String novo,String contribuinte){
            for(Cliente x: this.clients){
                if(x.getContribuinte().equals(contribuinte)){
                    x.setNome(novo);
                }
            }
        }
        
        public void mudacontribuinte(String novo,String contribuinte){
            for(Cliente x: this.clients){
                if(x.getContribuinte().equals(contribuinte)){
                    x.setContribuinte(novo);
                }
            }
        }
        public void mudamorada(String novo,String contribuinte){
            for(Cliente x: this.clients){
                if(x.getContribuinte().equals(contribuinte)){
                    x.setMorada(novo);
                }
            }
        }
        //Quantidade de clientes   
        public int quantClientes(){
            return this.clients.size();
        }
        
        public int getSize(){
            return(this.clients.size());
        }
        
        public Cliente getCliente(String contribuinte){
            Cliente aux=new Cliente();
            for(Cliente x: this.clients){
                if(x.getContribuinte().equals(contribuinte)){aux=x.clone();}
            }
            return aux;
        }
        
        //Adicionar um cliente
        public void addCliente(Cliente novo){        
                this.clients.add(novo.clone());
        }
        
        
        //Remove um cliente    
        public void removeCliente(Cliente removido){
                this.clients.remove(removido);
        }
        
        public void removeCliente_Contribuinte(String contribuinte){
            for(Cliente x: this.clients){
                if(x.getContribuinte().equals(contribuinte)){
                    System.out.println("\nCliente "+ x.getNome() +" apagado.\n");
                    this.clients.remove(x);
                }
            }
        }
        
        public void mostrarOrdenados(TreeSet<Cliente> aux){
            
            for(Cliente x: this.clients)aux.add(x);
            for(Cliente x: aux)x.toString();
            }
            
        public String toString(){
            StringBuilder s = new StringBuilder();
            for(Cliente x : this.clients){
                //s.append("Cliente :"+ it.getNome());
                s.append(x.toString());
                s.append("\n");
                
            }
            return(s.toString());
    }
        
        public void gravaBin (String nomeFicheiro) throws IOException {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(nomeFicheiro));
            
            oos.writeObject(this);
            oos.flush();
            oos.close();
        }
    
        public void addServico(String contribuinte,Produto y){
            for(Cliente x: this.clients){
                if(x.getContribuinte().equals(contribuinte)){x.addProduto(y);}
            }
        }
        
    }
    Cliente :
    Java Code:
    import java.util.*;
    public class Cliente 
    {
        //Variaveis de instancia
        
        private String nome;
        private String morada;
        private String numero_contribuinte;
        private ArrayList<Produto> serviços;
        
        //métodos de instancia
       
        public ArrayList<Produto> getServiços(){
            return this.serviços;
        }
        
       public void setNome(String novo){
           this.nome=novo;
        }
        
       public String getNome(){
        return this.nome;
        }
        
       public void setMorada(String novo){
           this.morada=novo;
        }
        
       public String getMorada(){
            return this.morada;
        }
        
       public void setContribuinte(String novo){
           this.numero_contribuinte=novo;
        }
        
       public String getContribuinte(){
            return this.numero_contribuinte;
        }
        
       // Construtores usuais
       
           
        public Cliente(){
            this.nome="";
            this.morada="";
            this.numero_contribuinte="";
            this.serviços=new ArrayList<Produto>();
        }
        
       public Cliente(String name, String address, String contribuinte) 
        {   this.nome =name; 
            this.morada = address;
            this.numero_contribuinte = contribuinte;
            this.serviços=new ArrayList<Produto>();
        }
        
        //Cópia de um veiculo
        
            public Cliente (Cliente v){
            this.nome=v.getNome();
            this.morada=v.getMorada();
            this.numero_contribuinte=v.getContribuinte();
            this.serviços=new ArrayList<Produto>();
            if (v.serviços.size()==0);
            else{
            for(int i=0;i<v.serviços.size();i++){
                this.serviços.add(v.serviços.get(i).clone()); 
            }
        }
        }
        
            public String toString(){
            StringBuilder s = new StringBuilder();
            s.append( "\nNome :" + this.nome+"\n" );
            s.append ("Morada :" + this.morada+"\n" );
            s.append ("Numero de Contribuinte :" + this.numero_contribuinte+"\n");
            for(int i=0;i<this.serviços.size();i++){
                s.append("Serviço" + i+"\n");
                this.serviços.get(i).toString();
            }
            return(s.toString());
        }
        
       public void addProduto(Produto novo){
           this.serviços.add(novo.clone());
        }
        
        public Cliente clone(){
            return new Cliente(this);
        }
        
        public double rendimento(){
            double res=0.0;
            for(int i=0;i<this.serviços.size();i++){
                res=res+this.serviços.get(i).calcular_preco_servico();
            }
            return res;
        }
        
        
        public boolean equals(Object obj) {
            if (this==obj) {return true;}
            if (obj == null && this.getClass() != obj.getClass()) {return false;}
            else {
                Cliente c = (Cliente)obj;
                return ((this.nome.equals(c.nome)) && (this.morada.equals(c.morada)) && (this.numero_contribuinte.equals(c.numero_contribuinte)));
            }
        }
    }
    I can take off the most easy methods if you think they are not necessary for you to be reading.
    Thanks.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Reading / Writing to a binary file

    Please fill in the details about what your program is doing. When you are trying to write the Clientes to a file, do you already have a Clientes object created, and is it filled with Client objects? Please tell us anything else we need to know to be able to help you.

  7. #7
    JeremyLin is offline Member
    Join Date
    Feb 2012
    Posts
    11
    Rep Power
    0

    Default Re: Reading / Writing to a binary file

    Quote Originally Posted by Fubarable View Post
    Please fill in the details about what your program is doing. When you are trying to write the Clientes to a file, do you already have a Clientes object created, and is it filled with Client objects? Please tell us anything else we need to know to be able to help you.
    Yeah, I create a new Client.
    Then try to write 'em to a file.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Reading / Writing to a binary file

    Quote Originally Posted by JeremyLin View Post
    Yeah, I create a new Client.
    Then try to write 'em to a file.
    OK, well best of luck to you then. If you still need our help, you'll want to take some time to provide more detail about your problem.

Similar Threads

  1. Reading a binary file
    By sigge in forum New To Java
    Replies: 2
    Last Post: 01-08-2012, 02:44 PM
  2. reading a from a binary file
    By trishtren in forum New To Java
    Replies: 2
    Last Post: 05-11-2011, 06:49 PM
  3. Replies: 3
    Last Post: 05-10-2009, 12:31 AM
  4. Reading a Field in a Binary File
    By janakiram.attuluri in forum Advanced Java
    Replies: 2
    Last Post: 01-09-2008, 11:47 AM
  5. reading a binary file with a RAF
    By jkurth in forum Advanced Java
    Replies: 2
    Last Post: 12-20-2007, 08:30 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •