简体   繁体   中英

EOFException while Deserializing object

I have created a method writeFile which writes directly to a File if the flag is true . If the flag is false it reads the File , retrieves the Object , appends something and again saves it to the File . I am getting EOFException when the flag is true .

Here is the whole class I am experimenting with:

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

You've already created a new empty file before you call readfile() when you're in 'append' mode, so of course you get EOF when trying to read an object. There aren't any. You need to call readfile() before creating the FileOutputStream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM