序列化java.util.Enumeration

时间:2012-08-29 05:48:25

标签: java serialization

我如何serialize Enumeration反对某个文件,然后deserialize呢?我尝试将其转换为ArrayList,但此选项对我不起作用。我尝试了以下代码:

FileOutputStream fos            = null;
ObjectOutputStream outs         = null;
Enumeration<TreePath> stateEnum = com.jidesoft.tree.TreeUtils.saveExpansionStateByTreePath(tree);
ArrayList<TreePath> pathList    = new ArrayList<TreePath>();

while(stateEnum.hasMoreElements()){
    pathList.add(stateEnum.nextElement());
}
try {
    fos = new FileOutputStream(TREE_STATE_FILE);
    outs = new ObjectOutputStream(fos);
    outs.writeObject(pathList);
    outs.close();
} catch (IOException e) {
    _log.info("Failed to create " + TREE_STATE_FILE + " file: ", e);
}

但是当我尝试serialize时,我得到了空值。 感谢

3 个答案:

答案 0 :(得分:1)

IMO,Enumeration的序列化并没有多大意义。 Enumeration仅仅是数据结构或其他业务逻辑顶部的浮动视图。为了序列化,您最好坚持序列化后备接口。为了可视化我正在写的内容,我设置了一个小代码片段:

import java.io.*;
import java.util.*;

import javax.swing.tree.TreePath;

public class EnumTest {

  public class MyEnumerator<T> {

    // set holding data
    List<T> data;

    public MyEnumerator(List<T> data) {
      this.data = data;
    }

    public List<T> getData() {
      return data;
    }

    public Enumeration<T> enumerate() {
      return new Enumeration<T>() {
        transient int i = 0;

        @Override
        public boolean hasMoreElements() {
          return i < data.size();
        }

        @Override
        public T nextElement() {
          return data.get(i++);
        }
      };
    }
  }

  public EnumTest() throws Exception {
    List<TreePath> TreePaths = Arrays.asList(new TreePath[] { new TreePath("3"), new TreePath("4"), new TreePath("5") });
    MyEnumerator<TreePath> myEnum1 = new MyEnumerator<TreePath>(TreePaths);
    print(myEnum1);

    FileOutputStream fos = new FileOutputStream("test.out");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(myEnum1.getData());
    oos.close();
    fos.close();

    System.out.println("* Serialization complete");

    FileInputStream fis = new FileInputStream("test.out");
    ObjectInputStream ois = new ObjectInputStream(fis);
    @SuppressWarnings("unchecked")
    List<TreePath> data = (List<TreePath>) ois.readObject();
    MyEnumerator<TreePath> myEnum2 = new MyEnumerator<TreePath>(data);
    print(myEnum2);

    System.out.println("* Deserialization complete");
  }

  private void print(MyEnumerator<TreePath> myEnum1) {
    Enumeration<TreePath> enm = myEnum1.enumerate();
    while (enm.hasMoreElements()) {
      System.out.println(enm.nextElement());
    }
  }

  public static void main(String[] args) throws Exception {
    new EnumTest();
  }
}

这通过持久化包含的数据并在之后重构包装类Enumeration来解决序列化MyEnumerator本身的问题。通过序列化/反序列化循环,您将得到一个不同的对象,但在语义上是相同的。

答案 1 :(得分:0)

要使代码正常工作,TreePath也必须是可序列化的,因为pathList的元素是TreePath对象。

答案 2 :(得分:0)

我不确定这是不是你的意思,但看看这段代码:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.NoSuchElementException;


@SuppressWarnings("unchecked")
public class SerializableEnumeration
   extends ArrayList
   implements Enumeration
{
   /** The serialVersionUID */
   private static final long serialVersionUID = 8678951571196067510L;
   private int index;

   public SerializableEnumeration () {
      index = 0;
   }

   public SerializableEnumeration (Collection c) {
      super(c);
      index = 0;
   }

   public SerializableEnumeration (int initialCapacity) {
      super(initialCapacity);
      index = 0;
   }

   public boolean hasMoreElements() {
      return (index < size());
   }

   public Object nextElement() throws NoSuchElementException
   {
      try {
         Object nextObj = get(index);
         index++;
         return nextObj;
      }
      catch (IndexOutOfBoundsException e) {
         throw new NoSuchElementException();
      }
   }

   private void writeObject(java.io.ObjectOutputStream out)
      throws java.io.IOException
   {
      // the only thing to write is the index field
      out.defaultWriteObject();
   }

   private void readObject(java.io.ObjectInputStream in)
      throws java.io.IOException, ClassNotFoundException
   {
      in.defaultReadObject();
   }
}

来自here