2014-02-25 54 views
1

如果标志为true,我创建了一个方法writeFile,它直接写入File。如果标志是false它读取File,检索Object,附加一些东西,然后再保存到File。当标记为true时,我得到EOFException反序列化对象时出现EOFException

这是全班同学,我有尝试:

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

回答

1

你已经创建了一个新的空文件调用ReadFile的()之前,当您在“追加”模式的时候,这样的当你试图读取一个对象时,你会得到EOF。没有任何。您需要在创建FileOutputStream之前调用readfile()。