Question

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

Was it helpful?

Solution

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)

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top