Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 反序列化对象时的EOFEException_Java_Serialization_Deserialization_Eofexception - Fatal编程技术网

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 ;
    }}`