如何反序列化文件?

时间:2018-04-28 16:07:17

标签: java serialization deserialization

我需要#3和#5的帮助。

  1. 创建一个集合并用1到15(含)之间的20个随机数填充

    List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(
            rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1),
            rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1),
            rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1),
            rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1), rand.nextInt(15 + 1)
       ));
    
  2. 打印数字

    System.out.println(list1);
    
  3. 使用值13为种子Random构造函数。

    • 播种ctor是什么意思?
  4. 将集合序列化为名为Numbers.ser

    的文件
    try (ObjectOutputStream serialize = new ObjectOutputStream(new FileOutputStream("src/serialize/Numbers.ser"))) {
        serialize.writeObject(list1);
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  5. 将文件反序列化为名为numberFromFile的新集合。删除所有重复的数字

    • 这是我对如何反序列化感到困惑的地方。解释是什么?

2 个答案:

答案 0 :(得分:0)

用种子初始化try(ObjectInputStream deserialize = new ObjectInputStream(new FileInputStream("src/serialize/Numbers.ser"))) { List<Integer> list2 = (List<Integer>) deserialize.readObject(); System.out.println(list2.stream().distinct().collect(Collectors.toList())); } catch(...) { ... } 意味着它将再次生成相同的随机数序列。只需查看文档:{​​{3}}

要从文件中读取不同的数字,您可以执行以下操作:

Oranges and lemons,
Pineapples and tea.
Orangutans and monkeys,
Dragonflys or fleas.

答案 1 :(得分:0)

//Seed the constructor of class Random with the value 13.
Random rand = new Random(13);

//Create a collection and fill it with 20 random numbers between 1 and 15 (inclusive)

List<Integer> list1 = new ArrayList<>();

for (int i = 0; i < 20; i++) {
    list1.add(rand.nextInt(15) + 1);  // Note here
}

//Print the numbers

System.out.println(list1);

//Serialize the collection to a file called Numbers.ser

try (ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream("Numbers.ser"))) {
    out.writeObject(list1);
} catch (IOException e) {
    e.printStackTrace();
}

//Deserialize the file into a new collection called numberFromFile. Remove all duplicate numbers
//this is where I am confused on how to deserialize. Can you someone explain this to me?
List<Integer> numberFromFile = null;
try (ObjectInputStream in = new ObjectInputStream(
        new FileInputStream("Numbers.ser"))) {
    numberFromFile = (List<Integer>) in.readObject();
} catch (Exception e) {
    e.printStackTrace();
}

//System.out.println(numberFromFile);

Set<Integer> distinct = new HashSet<>(numberFromFile); 
System.out.println(distinct);