Connor Murray
Connor Murray

Reputation: 17

FileNotFoundException when trying to save game

When I attempt to save my android game (played via Android simulator on my Windows laptop), I get a FileNotFoundException. I have spent hours trying different things, but remain perplexed as the code works perfectly on my previous version not for Android.

FileOutputStream saveStream;
ObjectOutputStream savePlayerObject = null;
String destinationFile = player1.getName() + ".txt";

try
{
   saveStream = new FileOutputStream(destinationFile);    
   savePlayerObject = new ObjectOutputStream(saveStream);   
   savePlayerObject.writeObject(player1);
}

catch(FileNotFoundException ex)
{
   Toast toast = Toast.makeText(getApplicationContext(), "Save Failed", Toast.LENGTH_LONG);
   toast.show();
}


catch(IOException ex)
{
   Toast toast = Toast.makeText(getApplicationContext(), "Save Failed", Toast.LENGTH_LONG);
   toast.show();
}


finally
{
   try
   {
      if(savePlayerObject !=null)
      {
         savePlayerObject.flush();    
         savePlayerObject.close();   
         Toast toast = Toast.makeText(getApplicationContext(), "Thank-You For Playing, See You Soon", Toast.LENGTH_LONG);
         toast.show();   
         System.exit(0);   
      }
   }

   catch(IOException ex)
   {
      Toast toast = Toast.makeText(getApplicationContext(), "Save Failed", Toast.LENGTH_LONG);
      toast.show();
   }
}

Upvotes: 1

Views: 92

Answers (2)

Mihai
Mihai

Reputation: 121

Maybe you don't have the necessary permissions to create new files.

Upvotes: 0

Mike Baranczak
Mike Baranczak

Reputation: 8394

It means that the program couldn't create the file at the specified location.

String destinationFile = player1.getName() + ".txt";

The file will be created in the current working directory. This is usually not what you want. You need to think about where exactly the file should go, then specify the absolute path.

Upvotes: 1

Related Questions