【问题标题】:Serialize JTree Object to file [closed]将 JTree 对象序列化为文件 [关闭]
【发布时间】:2021-02-13 05:53:34
【问题描述】:

我正在尝试将 JTree 对象序列化为文件。

这就是我的做法:

FileOutputStream f = new FileOutputStream(new File("serialisation2.txt"));
ObjectOutputStream o = new ObjectOutputStream(f);

// Write objects to file
o.writeObject(jTree1);
                   
o.close();
f.close();

然后我试图用这个来阅读它:

FileInputStream fi = new FileInputStream(new File("serialisation2.txt"));
ObjectInputStream oi = new ObjectInputStream(fi);
try{
   while(true){
          jTree2 = new javax.swing.JTree(raíz);

  System.out.println(oi.toString());
          jTree2 = (JTree) oi.readObject();
  }
}

但问题是,当我执行 oi.readObject(); 时,它会返回 java.io.EOFException

有什么想法吗?

【问题讨论】:

  • 看起来像预期的行为。您正在使用while(true) 无限期地阅读它,因此当它到达流的末尾时会抛出异常。还有为什么你用new创建一个对象,然后立即将流中的一个对象分配给同一个变量?
  • 我删除了 while 并且 Stills 抛出了异常,我正在阅读如果我能以其他方式或其他方式做到这一点......
  • @syzygysyzygy 请edit您的问题包含minimal reproducible example,其他人可以编译和测试。还包括完整的异常消息,包括堆栈跟踪,您的问题。
  • 没有while 循环就无法复制。
  • “有什么想法吗?” 首先:序列化树模型,而不是树。 GUI 序列化组件没有好的案例。第二:对象输出流不会序列化为文本,因此将其称为.txt 文件是不正确的,并且会欺骗操作系统尝试在文本编辑器中打开它。男人会添加一个.obj 扩展名,以明确它是不是文本。一般提示:为了尽快获得更好的帮助,edit 添加minimal reproducible exampleShort, Self Contained, Correct Example。 2) 使用逻辑一致的形式缩进代码行和块。 ..

标签: java swing jtree


【解决方案1】:

去掉while循环,你真的不需要jTree2 = new javax.swing.JTree(raíz);只要jtree2就可以得到反序列化的值。阅读更多关于序列化herehere

FileInputStream fi = new FileInputStream(new File("serialisation2.txt"));
ObjectInputStream oi = new ObjectInputStream(fi);
jTree2 = (JTree) oi.readObject();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 2013-07-14
    • 2015-02-23
    • 2011-04-09
    相关资源
    最近更新 更多