1

我创建了一个writeFile直接写入 a Fileif flag is 的方法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 ;
    }}`
4

1 回答 1

1

当您处于“追加”模式时,您在调用 readfile() 之前已经创建了一个新的空文件,因此在尝试读取对象时当然会得到 EOF。没有。您需要在创建 FileOutputStream 之前调用 readfile()。

于 2014-02-25T22:23:43.707 回答