gpt4 book ai didi

java - 序列化 java.util.Enumeration

转载 作者:行者123 更新时间:2023-11-30 11:41:40 25 4
gpt4 key购买 nike

我如何序列化 Enumeration 对象到一个文件,然后反序列化它?我试图将其转换为 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);
}

但是当我尝试对其进行序列化时,我得到了空值。谢谢

最佳答案

IMO,Enumeration 的序列化并没有多大意义。 Enumeration 只是数据结构或其他业务逻辑之上的 float View 。为了序列化,你最好坚持序列化支持接口(interface)。为了可视化我正在写的内容,我设置了一个小代码片段:

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。通过序列化/反序列化循环,您将获得一个不同的对象,但在语义上是相同的。

关于java - 序列化 java.util.Enumeration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12171614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com