ObjectInputStream覆盖所有数据

时间:2015-11-08 04:08:32

标签: java objectinputstream objectoutputstream

似乎对象输出流可能充满了诱杀陷阱。目前,我相信我的输出流正常工作,但是当我尝试从文件读入时,所有数据都被覆盖了我正在使用的hashmap。 大多数情况下,hashmap值的int不为0,但是当我从文件中检索对象时,hashmap的每个键值都为0。

这是我的问题的伪/真实代码。

写作:

HashMap<State, int> temp= new HashMap <state, int>();

    try{
    FileOutputStream fileOut = new   FileOutputStream("/Users/_____/Documents/hash.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut);
             out.reset(); //added before and after for testing.

             //iterating through hash to see if everything is correct before outputting. (and it is)
             Set set = hash.entrySet();
             // Get an iterator
             Iterator i = set.iterator();
             // Display elements
             while(i.hasNext()) {
                Map.Entry me = (Map.Entry)i.next();
                temp.put((state)me.getKey(), (int)me.getValue());

                //output is as expected
                System.out.println("Serializing "+me.getValue() + "\n\n\n");

           }


             //using flush and reset hoping for effect.
             //tried using write(temp)
             out.writeUnshared(temp);
             out.flush();
             out.reset();
             out.close();

             fileOut.close();

          }catch(IOException i){
              i.printStackTrace();
          }

输入(经过多次调试后,错误似乎在这里)。

 try
          {
             FileInputStream fileIn = new FileInputStream("/Users/_____/Documents/hash.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn);


         HashMap<state, int> temp= new HashMap <state, int>();

         //hash = (HashMap) in.readObject();

         temp=(HashMap) in.readObject();
         Set set = temp.entrySet();
         // Get an iterator
         Iterator i = set.iterator();
         // Display elements
         while(i.hasNext()) {
            Map.Entry me = (Map.Entry)i.next();
            hash.put((state)me.getKey(), (int)me.getValue());

            //Always is 0.
            System.out.println("Getting IN "+me.getValue() + "\n\n\n");

       }



         in.close();
         fileIn.close();
      }catch(IOException i)
      {
         i.printStackTrace();
         return;
      }catch(ClassNotFoundException c)
      {
         System.out.println("class not found");
         c.printStackTrace();
         return;
      }

0 个答案:

没有答案