What I am trying to do is writing a HashMap to a file. The code below correctly when run at once. However when i try to run just writing the object to the file and try to just run reading the written object to file individually it throws the following exception.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
public class FileIo {
String fileName;
FileOutputStream fos;
FileInputStream fis;
ObjectOutputStream oos;
ObjectInputStream ois;
public FileIo(String fileName) {
this.fileName = fileName;
File file = new File(fileName);
try {
if (!file.exists()) {
file.createNewFile();
System.out.println("created");
}
fos = new FileOutputStream(fileName);
fis = new FileInputStream(fileName);
oos = new ObjectOutputStream(fos);
ois = new ObjectInputStream(fis);
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeToFile(Object obj) {
try {
oos.writeObject(obj);
oos.flush();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public Object readFromFile() {
try {
return ois.readObject();
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
public static void main(String args[]) {
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
FileIo fi = new FileIo("tex.txt");
//Only write to the file
ArrayList<String> a = new ArrayList<>();
a.add("test");
map.put("testput", a);
fi.writeToFile(map);
//Only write to the file
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Only read from the file
map = null;
map = (HashMap<String, ArrayList<String>>) fi.readFromFile();
System.out.println(map.toString());
}
}
//Exception
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2608)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371)
at FileIo.readFromFile(FileIo.java:49)
at FileIo.main(FileIo.java:73)
The only thing happening different is instead of directly writing and instantaneously reading it. I first write the object program finishes then run the program runs to read the object.
You need to create the FileInputStream
after the data has been written to the file.
You can't create it before and assume it will show subsequently written data.