java 序列化指定顺序,java - 如何将两种不同的列表类型序列化/反序列化为单个顺序文件 - SO中文参考 - www.soinside.com...

我有三个不同的联系类型列表,我需要序列化到一个文件,然后在需要时检索这些列表(反序列化)。我已经考虑过使用hashmap但我并不熟悉,而且我确定如何检索完整的列表。任何想法都表示赞赏。

我不确定我是否可以在hashmap中使用Object类型。这是我能够将所有三个列表添加到hashmap的一种方式。另外,我需要知道从hashmap中检索这些列表的正确方法,如果这是最好的方法。

public class Controller()

{

// the list objects I need to serialize

List friendContacts = new ArrayList();

List fdContacts = new ArrayList<>(friendContacts);

List familyContacts = new ArrayList();

List fContacts = new ArrayList<>(familyContacts);

// methods to retrieve the lists and list items

}

//Serialization code

public class Serialization

{

public void serialize(HashMap lists, String fileName)

{

// serializes the hashmap passed from calling method

try (ObjectOutputStream output =

new ObjectOutputStream(new FileOutputStream(fileName)))

{

output.writeObject(lists);

output.close();

}

catch(IOException ex)

{

System.out.println(ex.getMessage());

ex.printStackTrace();

}

}

@SuppressWarnings("unchecked")

public HashMap deserialize(String fileName)

{

try (ObjectInputStream input =

new ObjectInputStream(new FileInputStream(fileName)))

{

HashMap lists = (HashMap)input.readObject();

System.out.println(lists.size());

input.close();

return lists;

}

catch (IOException | ClassNotFoundException ex)

{

if(ex.getClass().getName() == "java.io.FileNotFoundException")

{

showErrorDialog("File Not Found", "Contacts.ser not found");

}

else

{

System.out.println(ex.getClass().getName());

System.out.println(ex.getMessage());

}

}

return null;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值