File saved in getFilesDir () lost on application restart

I'm new to Android programming, so the answer to my question will hopefully be easy.

I have an application that can receive a file from a PC program that connects over the network. This file is then saved internally and used by the application. When the application starts up, it reads a file (which is a serialized instance of the "WordList" class, which is basically a HashMap) and displays the data from the user. At any time, the pc program can send a new file to the Android device, which receives the file and overwrites the old one in memory.

The file is retrieved and saved as follows:

try(ServerSocket serverSocket = new ServerSocket(port)){

    Socket pc = serverSocket.accept();
    ObjectInputStream ois = new ObjectInputStream(pc.getInputStream());
    list = (WordList)ois.readObject();
    ois.close();
    pc.close();

 }catch(IOException | ClassNotFoundException e){
     //Display error message and stuff
 }

 try {
     ObjectOutputStream oos = new ObjectOutputStream(
                               openFileOutput("save.dat", Context.MODE_PRIVATE));
     oos.writeObject(list);
     oos.flush();
     oos.close();
 } catch (IOException e) {
     //Display error message and stuff
 }

      

When the application starts up, it reads the file as follows:

if (new File(getFilesDir() + "save.dat").exists()) {

     try {
         ObjectInputStream ois = new ObjectInputStream(
                                  new FileInputStream(getFilesDir() + "save.dat"));
         WordList list = (WordList)ois.readObject();

         /*Now set a reference to the list object so it can be used by the app, 
         then start displaying stuff to the user...*/
         ModelController.getInstance().setList(list);
         ModelController.getInstance().start(this);
     }catch(IOException | ClassNotFoundException e){
         //Display error message and stuff
     }
 }else{ 
     //Display error message and stuff
 }

      

The problem is that the application cannot find the file when it starts. If I send a new file from the PC, it will be received and used correctly, with no error messages. But if I restart the application, it is not found, I get an error from the "else" part of the last block of code. What am I forgetting?

+3


source to share


2 answers


new File(getFilesDir() + "save.dat")

      

it should be

new File(getFilesDir(), "save.dat")

      

the latter adds a file separator between the return value getFilesDir()

and"save.dat"

Instead of using



  new FileInputStream(getFilesDir() + "save.dat")

      

us

openFileInput("save.dat")

      

Here you can find the documentation

+3


source


You can probably check where save.dat is located on disk.

My hypothesis is to change the persistence:



ObjectOutputStream oos = new ObjectOutputStream(
                     openFileOutput(getFilesDir() + "save.dat", Context.MODE_PRIVATE));

      

0


source







All Articles