从序列化文件加载列表

时间:2017-04-28 23:23:29

标签: java serialization file-io objectoutputstream

对于大学项目,我必须将列表的散列图保存到二进制文件中。然后我必须能够再次加载它,但我有一点麻烦。它将保存我的文件但不会加载它。这是我的代码:

这是保存:

private static void storeRec() 
{


    try
    {
        File f = new File("recommendation.dat");
        if(!f.exists())
        {
            f.createNewFile();
        }   
        FileOutputStream fos=new FileOutputStream(f);
        ObjectOutputStream oos=new ObjectOutputStream(fos);

        oos.writeObject(localStore);
        oos.flush();
        oos.close();
        fos.close();
        System.out.println("Recommendation read to File");


    } 
    catch (IOException ex) 
    {
        Logger.getLogger(Project2.class.getName()).log(Level.SEVERE, null, ex);
    }



}

这是加载代码:

 List<Recommendation> newmovies = new ArrayList<>();

    try
    {
        File f = new File("recommendation.dat");
        if(f.exists())
        {
            DataInputStream dis = new DataInputStream(new FileInputStream(f));
            /*FileInputStream streamIn = new FileInputStream(f);
            ObjectInputStream dis = new ObjectInputStream(streamIn);*/
            while(dis.available()>0)
            {
                byte[] titleBytes = new byte[32];
                dis.read(titleBytes);
                String title = new String(titleBytes);
                byte[] queryBytes = new byte[32];
                dis.read(queryBytes);
                String query = new String(queryBytes);
                byte[] directorBytes = new byte[32];
                dis.read(directorBytes);
                String director = new String(directorBytes);
                byte[] summaryBytes = new byte[64];
                dis.read(summaryBytes);
                String summary = new String(summaryBytes);

                byte[] categoryBytes = new byte[18];
                dis.read(categoryBytes);
                String category = new String(categoryBytes);  
               //String category = dis.readUTF();
                double rating = dis.readDouble();
                int release = dis.readInt(); 
                byte[] castBytes = new byte[64];
                dis.read(castBytes);
                String cast= new String(castBytes);
                ArrayList<String> castArrayList = new ArrayList<>(Arrays.asList(cast.split(",")));
                int myRating = dis.readInt();
                byte[] commentsBytes = new byte[32];
                dis.read(commentsBytes);
                String myComments = new String(commentsBytes);

                newmovies.add(new Recommendation(title,query,director,summary,release,category,rating,castArrayList,myRating,myComments));
                //System.out.println(newmovies);
                localStore.put(query, newmovies);

            }
        }

LocalStore是我想要将文件中的数据添加到的哈希映射。关键是查询。由于某种原因,它不会添加到地图

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您必须对ObjectInputStreamObjectOutputStream创建的文件使用readObject()来阅读writeObject()撰写的对象。

并且available()不是流结束的有效测试。见Javadoc。你必须抓住EOFException