将对象写入二进制文件时出错

时间:2012-10-17 23:49:41

标签: java serialization filenotfoundexception

所以,这是我的代码:

try  
{  
  PlayerSave save = new PlayerSave(this);   
  save.playerLooks = look;        
  File test = new File("C:/cache/" + playerName + ".tmp");  
  test.createNewFile();  
  FileOutputStream f_out = new  
      FileOutputStream("C:/cache/" + playerName + ".tmp");  
  ObjectOutputStream obj_out = new ObjectOutputStream (f_out);  
  obj_out.writeObject (save);  
  obj_out.close();  
  f_out.close();  
}  
catch (Exception e)  
{  
  e.printStackTrace();  
} 

执行时,我收到以下错误:

java.io.FileNotFoundException: C:\cache\Bobdole.tmp (The system cannot find the path specified)

我也试过使用这段代码:

    try
    {
      PlayerSave save = new PlayerSave(this); 
      save.playerLooks = look;      
//      File test = new File("C:/cache/" + playerName + ".tmp");
//      test.createNewFile();
      FileOutputStream f_out = new
          FileOutputStream("C:/cache/" + playerName + ".tmp");
      ObjectOutputStream obj_out = new ObjectOutputStream (f_out);
      obj_out.writeObject (save);
      obj_out.close();
      f_out.close();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }

但是,它会产生相同的错误。我很困惑为什么这不起作用,因为一切似乎都是正确的。如果你们能解决那些有用的问题。 谢谢!

2 个答案:

答案 0 :(得分:2)

这告诉你目录C:\cache不存在。该目录必须存在才能使您能够向其写入文件。您可以手动创建它,也可以使用以下内容创建它:

File directory = new File("C:\\cache");
directory.mkdir();

答案 1 :(得分:0)

程序找不到您的文件夹。