1

This is for a homework I'm doing on my walk learning java.

I'm writing a program and it is all working as expected except the read/write to file.

I have one class named Medico that holds only one string (typeOfMedico) and one int (valorFacturado). Medico is a sub class of Pessoa. Pessoa holds data like name and address. public class Medico extends Pessoa implements Serializable is the main function on Medicoclass.

On my main class, named Clinica, I ask for user input and at the end of I create a new Medico that its added to an Arraylist named medico.

For reading and writing to file I've created this class:

package clinica;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class FicheiroObjectos {

    private ObjectInputStream iS;
    private ObjectOutputStream oS;

    public void abreLeitura(String nomeDoFicheiro) throws IOException {
        iS = new ObjectInputStream(new FileInputStream(nomeDoFicheiro));
    }

    public void abreEscrita(String nomeDoFicheiro) throws IOException {
        oS = new ObjectOutputStream(new FileOutputStream(nomeDoFicheiro));
    }

    public Object leObjecto() throws IOException, ClassNotFoundException {
        return iS.readObject();
    }

    public void escreveObjecto(Object o) throws IOException {
        oS.writeObject(o);
    }

    public void fechaLeitura() throws IOException {
        iS.close();
    }

    public void fechaEscrita() throws IOException {
        oS.close();
    }

    public void leFicheiroMedicos() {
        Medico medicos;
        while (true) {
            try {
                medicos = (Medico) this.leObjecto();
                Clinica.medicos.add(medicos);
            } catch (EOFException eof) {
                break;
            } catch (ClassNotFoundException cnf) {
                System.out.print("\nClassNotFoundException!\nO programa vai terminar\n");
                System.exit(-1);
            } catch (IOException ioe) {
                System.out.print("\nErro ao ler o ficheiro!\nO programa vai terminar\n");
                System.exit(-1);
            }
        }
    }

    public void escreveFicheiroMedicos() {
        try {
            for (Medico medicos: Clinica.medicos) {
                this.escreveObjecto(medicos);
            }
        } catch (IOException e) {
            System.out.print("\nErro ao escrever no ficheiro!\nO programa vai terminar\n");
            System.exit(-1);
        }
    }
}

On my main class I've created this two functions:

 public static void insereDadosExistentes() {

        try {
            FicheiroObjectos file = new FicheiroObjectos();
            file.abreLeitura("Medicos.dat");
            file.leFicheiroMedicos();
            file.fechaLeitura();
        } catch (IOException ioe) {
        }

    }


    public static void gravarMedicos() {

        try {
            FicheiroObjectos file = new FicheiroObjectos();
            file.abreEscrita("Medicos.dat");
            file.escreveFicheiroMedicos();
            file.fechaEscrita();
        } catch (IOException e) {
            System.out.print("\nErro ao escrever no ficheiro!\nO programa vai terminar\n");
            System.exit(-1);
        }

    }
}

Then added insereDadosExistentes() at the beginning of my mainfunction and added gravarMedicos() just after adding a Medico to my medicos arraylist.

When I run my program (On the first run, file Medicos.dat, does not exist) and create a Medico, Medico is added to my arraylist and the file Medicos.dat is created. Then I stop the program and on the next run, which now haves a Medicos.dat file, I get the error:

Erro ao ler o ficheiro!
O programa vai terminar

The problem is in writing the file or reading the file? I know the error is given when reading the file but it could be because the writhing to file is not properly executed.

If I try to open Medicos.dat I can see some characters but nothing related with the info I input so I don't even know if the file writing is ok.

Remember that all besides file handling is working as expected.

Can you point me In some directions?

favolas

9
  • Please translate program output to English! That seems to mean.. "Error reading the file! The program will end". Commented Dec 29, 2011 at 0:31
  • 1
    Instead of that output line, put e.printStackTrace(). Commented Dec 29, 2011 at 0:32
  • I thought it was a fun way to practice Portuguese. This was Portuguese, right? :) Commented Dec 29, 2011 at 0:34
  • @Andrew Thompson that is exactly what you translated Commented Dec 29, 2011 at 0:34
  • 1
    @sarnold (definitely) OT: From what I know of Brazilians - they seem to know how to enjoy life. So everybody could use some more Brazilian friends. ;) Commented Dec 29, 2011 at 0:44

4 Answers 4

3
  1. Make sure that you explicitly close the ObjectOutputStream so that all the data is written.

  2. Your problem is an IOException. However, the backtrace will tell you what's going on: trouble opening, reading, what? you can call printStackTrace(), but better you can use a debugging and just look at the stack trace.

Sign up to request clarification or add additional context in comments.

2 Comments

I've closed the ObjectOutputStream and problem persists. printStackTrace() gives me Caused by: java.io.InvalidClassException: clinica.Medico; no valid constructor but looking at my constructor I can't see what the problem is
Well, does Medico have a no-args constructor? I think that's required.
2

If you catch an exception dont just write something to system.out but print the stacktrace this will usually give you a clue whats wrong

try {
            FicheiroObjectos file = new FicheiroObjectos();
            file.abreEscrita("Medicos.dat");
            file.escreveFicheiroMedicos();
            file.fechaEscrita();
        } catch (IOException e) {
           e.printStackTrace();
        }

Comments

1

Q: Are you trying to read and write DATA, or are you trying to serialize and deserialize OBJECTS?

I think all you need to do is open and write to a simple text file:

For example:

http://www.exampledepot.com/egs/java.io/AppendToFile.html

import java.io.*;

public class TestFile
{
  public static void main (String[] args)
  {
    // Test "append"
    // SOURCE: http://www.exampledepot.com/egs/java.io/AppendToFile.html
    try {
        BufferedWriter out = 
          new BufferedWriter(
            new FileWriter("myfile.txt", true));
        out.write("testing: a b c\n");
        out.write("testing: d e f\n");
        out.close();
    } 
      catch (IOException e) {
    }
  }
}

Sample output:

testing: a b c 
testing: d e f

3 Comments

I have to write to a Objects file
Well then you're going to get a binary file. With the header string "CAFEBABE" ;) java.sun.com/developer/technicalArticles/Programming/…
Isn't that for writing text files?
0

I don't know Java's serialization stuff at all, but this seems "too easy":

public void escreveObjecto(Object o) throws IOException {
    oS.writeObject(o);
}

How is the object output stream supposed to know what portions of your object needs to be written to disk? Could be that your object contains nothing but computed values that shouldn't be stored. Could be that your object's data needs to be stored completely. Perhaps references to String objects should just be dropped... or perhaps those Strings should be written to disk.

There must be more to using the ObjectStream stuff than you're showing here -- and paulsm4's answer shows how writing your own content by hand isn't too bad. Should you be taking that approach instead? Does your class have a defined storage format that you must adhere to?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.