我要做的是将HashMap写入文件。一次运行时,下面的代码正确。但是,当我尝试运行只是将对象写入文件并尝试只是单独运行读取写入对象时,它会引发以下异常。
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());
}
}
//异常
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)
唯一不同的是,不是直接写作和即时阅读。我先写对象程序完成然后运行程序运行来读取对象。
答案 0 :(得分:5)
您需要在将数据写入文件后创建FileInputStream
。
您之前无法创建它并假设它将显示随后的书面数据。