java - 反序列化对象时出现 EOFException

标签 java serialization deserialization eofexception

我创建了一个方法writeFile,如果标志为true,它会直接写入File。如果该标志为false,它将读取File,检索Object,附加一些内容,然后再次将其保存到File。当标志为 true 时,我收到 EOFException

这是我正在尝试的整个类(class):

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

最佳答案

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

关于java - 反序列化对象时出现 EOFException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22020334/

相关文章:

相当于 JavaScript 的 String.match() 的 Java

java - boolean 示例返回意外答案

c# - 是否可以将 Protobuf-Net 与没有无参数构造函数的类一起使用?

c# - 在类之前删除 [Serializable] 属性

c# - 加载对象时的反序列化问题

c++ - 序列化一个定义未知的结构

wcf - 强制 WCF 在反序列化期间使用现有缓冲区?

java - 如何从菜单栏打开新窗口?

java - Selenium 选择第一个日期选择器正在工作,但没有选择第二个

.net - Json.net松散vs严格类型反序列化