我创建了一个方法writeFile
,如果标记为File
,则会直接写入true
。如果标记为false
,则会显示File
,检索Object
,附加内容并再次将其保存到File
。当标志为EOFException
时,我收到true
。
以下是我正在尝试的全班:
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 ;
}}`
答案 0 :(得分:1)
当你处于'追加'模式时,你已经在调用readfile()之前创建了一个新的空文件,所以你在尝试读取一个对象时当然会得到EOF。没有。您需要在创建FileOutputStream之前调用readfile()。