deserialise文件,然后将内容存储在ArrayList <string>中。 (Java)的

时间:2016-12-27 00:10:33

标签: java arraylist deserialization fileinputstream objectinputstream

假设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中

1 个答案:

答案 0 :(得分:0)

将其投放到ArrayList<String>,因为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强制转换为泛型类型。使用Java的类型擦除,如果转换在运行时是类型安全的,则无法知道编译器。 Here是另一篇文章。此外,e.getMessage();无效,打印或使用e.printStackTrace();代替。