Java 反序列化对象时的EOFEException
我创建了一个方法Java 反序列化对象时的EOFEException,java,serialization,deserialization,eofexception,Java,Serialization,Deserialization,Eofexception,我创建了一个方法writeFile,如果标志为true,它将直接写入文件。如果标志为false,它将读取文件,检索对象,添加内容,然后再次将其保存到文件。当标志为true时,我得到EOFEException 以下是我正在试验的整个课程: 在“附加”模式下调用readfile()之前,您已经创建了一个新的空文件,因此在尝试读取对象时,您当然会得到EOF。没有。在创建FileOutputStream之前,需要调用readfile() public class HandleObjects{ pub
writeFile
,如果标志为true
,它将直接写入文件。如果标志为false
,它将读取文件
,检索对象
,添加内容,然后再次将其保存到文件
。当标志为true
时,我得到EOFEException
以下是我正在试验的整个课程:
在“附加”模式下调用readfile()之前,您已经创建了一个新的空文件,因此在尝试读取对象时,您当然会得到EOF。没有。在创建FileOutputStream之前,需要调用readfile()
public class HandleObjects{
public final static String PATH = "/home/user/Desktop/exp.conf" ;
public static boolean i = true ;
public static void main(String[] args) throws JSONException, IOException, ClassNotFoundException {
JSONObject obj = new JSONObject();
obj.put("id", "something");
JSONObject obj1 = new JSONObject();
obj1.put("key", "xxxxxxxxxxxxxxx");
obj1.put("token", "xxxxxxxxxxxxx");
writeFile(obj,false);
readFile();
writeFile(obj1,true); // Exception occurs here
readFile();
}
public static void writeFile(JSONObject o, boolean flag ) throws FileNotFoundException, IOException, JSONException, ClassNotFoundException{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(PATH)) ;
JSONObject ob = null ;
if (flag){
ob = readfile();
ob.append("extra", o);
os.writeObject(ob.toString());
}
else{
os.writeObject(o.toString());
}
os.flush() ;
os.close();
}
public static JSONObject readFile() throws FileNotFoundException, IOException, JSONException, ClassNotFoundException{
ObjectInputStream is = new ObjectInputStream(new FileInputStream(PATH)) ;
String str= (String) is.readObject() ;
JSONObject o = new JSONObject(str);
is.close() ;
return o ;
}}`