1

假设serialise.bin是一个文件,是满语的,被一个ArrayList时,它是序列化反序列化文件,然后将内容存储在ArrayList <String>中。 (JAVA)

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; 
} 

我希望能够deserialise了“serialise.bin”文件和存储内容在一个ArrayList

+0

你的问题是什么?你的代码有问题吗? – shmosel

+0

不要返回'ArrayList'。相反,返回List,这样'deserialise'的调用者就不会依赖于那个实现细节。 –

回答

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; 
} 

注释可以添加0来抑制类型安全警告。它会发生,因为您必须将Object转换为通用类型。使用Java的类型擦除如果在运行时转换是类型安全的,则无法知道编译器。 Here是另一篇文章。此外e.getMessage();不做任何事,打印它或使用e.printStackTrace();

+0

感谢您的帮助,它的工作原理,但我必须添加一个“@SuppressWarnings(”unchecked“)”。我不确定这是什么,但一旦它被添加,我不再收到关于“类型安全性:从对象到ArrayList ”的警告。“ –

+0

你是对的,你无法避免这个警告,只是压制它。更新了答案。 – thatguy

+0

是@SupressWarnings(“unchecked”)好的代码吗?在这种情况下,我会保持它,因为我可以想到另一种方式。 –

相关问题