views:

41

answers:

2

Hi, I am trying to write an Object of kind "HashMap" to a file & recover it when my program run again. But I faced with an EOFException when I try to read that object and the Object is not read from the file. I use the flush() & close() methods when I wrote the object for the FileOutputStream & ObjectOutputStream. Also I create OutputStream & InputStream together for my file. here is my code:

DataOutputStream outToFile;
DataInputStream inFromFile;

ObjectOutputStream writeTableToFile;
ObjectInputStream readTableFromFile;
File tableFile;

public DNS(){
    try {
        tableFile = new File("table.txt");
        outToFile = new DataOutputStream(new FileOutputStream(tableFile) );
        writeTableToFile = new ObjectOutputStream(outToFile);

        inFromFile = new DataInputStream(new FileInputStream(tableFile));
        readTableFromFile = new ObjectInputStream(inFromFile);
        HashMap table2 = (HashMap) readTableFromFile.readObject();
        if (table2 == null)
            table=new HashMap(100);
        else
            table = table2;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch(EOFException e){
        table=new HashMap(100);
    }
    catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

}

and here is code for writing object:

            table.put(NameField.getText(), IPField.getText());
            try {
                //writeTableToFile.reset();
                writeTableToFile.writeObject(table);
                writeTableToFile.flush();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

Regards, sajad

A: 

EOFException means that the file is incomplete. So it's either not flush()ed or not close()ed or an exception is swallowed somewhere.

Aaron Digulla
Mr! I used flush() in my code. also when closing program I used close(). I saw the file; it is not empty.
sajad
It was empty when you read it because you had just created a new one and not written to it yet.
EJP
A: 

The file seems to be incomplete. When I look at your code, you're creating the file table.txt and try to read it immediately afterwards.

This ctor:

new FileOutputStream(tableFile)

will overwrite the file. If your read it afterwards, it will be empty (except the header information from the OOS)

Ulf Jaehrig
sajad
Yes, you should ever only have one of them open for any single file at one time.
Aaron Digulla
Aaron Digulla