1

フラグがwriteFileの場合に直接書き込むメソッドを作成しました。フラグが の場合、 を読み取り、を取得し、何かを追加して、 に再度保存します。フラグが のときに取得しています。FiletruefalseFileObjectFileEOFExceptiontrue

これが私が実験しているクラス全体です:

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 に答える