【问题标题】:deserialise file, then store content in ArrayList<String>. (java)反序列化文件,然后将内容存储在 ArrayList<String> 中。 (爪哇)
【发布时间】:2023-03-19 08:00:01
【问题描述】:

假设serialise.bin是一个充满单词的文件,序列化时是一个ArrayList

public static ArrayList<String> deserialise(){
    ArrayList<String> words= new ArrayList<String>();
    File serial = new File("serialise.bin");
    try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(serial))){ 
        System.out.println(in.readObject());   //prints out the content
    //I want to store the content in to an ArrayList<String>
    }catch(Exception e){
        e.getMessage();
    }
return words;
}

我希望能够反序列化“serialise.bin”文件并将内容存储在 ArrayList 中

【问题讨论】:

  • 你有什么问题?你的代码有问题吗?
  • 不要返回ArrayList。相反,返回List,这样deserialise 的调用者就不会依赖于该实现细节。

标签: java arraylist deserialization fileinputstream objectinputstream


【解决方案1】:

将其转换为ArrayList&lt;String&gt;,因为in.readObject() 确实返回Object,并将其分配给words

@SuppressWarnings("unchecked")
public static ArrayList<String> deserialise() {

    // Do not create a new ArrayList, you get
    // it from "readObject()", otherwise you just
    // overwrite it.
    ArrayList<String> words = null;
    File serial = new File("serialise.bin");

    try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(serial))) { 
        // Cast from "Object" to "ArrayList<String>", mandatory
        words = (ArrayList<String>) in.readObject();
    } catch(Exception e) {
        e.printStackTrace();
    }

    return words;
}

可以添加注释@SuppressWarnings("unchecked") 以抑制类型安全警告。它会发生,因为您必须将 Object 强制转换为 generic 类型。使用 Java 的类型擦除,编译器无法知道强制转换在运行时是否是类型安全的。 Here 是关于此的另一篇文章。而且e.getMessage();什么都不做,打印出来或者改用e.printStackTrace();

【讨论】:

  • 感谢您的帮助,它可以工作,但我必须添加一个“@SuppressWarnings("unchecked")”。我不确定这是做什么的,但是一旦添加它,我就不再收到有关“类型安全:从对象到 ArrayList 的未经检查的强制转换”的警告
  • 你是对的,你无法避免这个警告,只是压制它。更新了答案。
  • @SupressWarnings("unchecked") 是好代码吗?在这种情况下,我会保留它,因为我能想到另一种方式。
  • 如果您可以避免警告,您应该从不禁止显示警告,因为它的存在是有原因的。但是,在某些情况下,这是不可能的,因此这样做是完全合理的。
猜你喜欢
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 2021-12-21
  • 2011-09-24
  • 1970-01-01
  • 2018-09-09
相关资源
最近更新 更多