2014-02-25 53 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()。