tags:

views:

70

answers:

2

I am trying to write an object (pilotRecord) to a file and read it back again. I understood that I didn't need to specify a path as it is internal to my app, so I want all files deleted if the app is uninstalled.

Here's my code:

    fileoutputstream = openFileOutput("test1", Context.MODE_WORLD_WRITEABLE);
    Log.d(this.getClass().getName(), "loadPilotRecord: "+fileoutputstream.toString());
    objectoutputstream = new ObjectOutputStream(fileoutputstream);
    Log.d(this.getClass().getName(), "loadPilotRecord: "+objectoutputstream.toString());
    objectoutputstream.writeObject(pilotRecord);
    objectoutputstream.close();
    fileoutputstream.close();

    fileinputstream = new FileInputStream("test1");
    Log.d(this.getClass().getName(), "loadPilotRecord: "+fileinputstream.toString());
    objectinputstream = new ObjectInputStream(fileinputstream);
    Log.d(this.getClass().getName(), "loadPilotRecord: "+objectinputstream.toString());
    pilotRecord = (PilotRecord)objectinputstream.readObject();
    objectinputstream.close();
    fileinputstream.close();

My problem is that I get a FileNotFoundException on the following line in the above code: fileinputstream = new FileInputStream("test1"); I'm not really sure how to find out what path it is using, or maybe there is a more obvious problem I'm just not seeing. Sorry if this is a bit basic, but I'm still trying to find my feet. The Log.d statements just output the class name and an Id.

TIA,

  • Frink
+1  A: 

To find out which path is actually used try: File f = new File("test1"); Log.d(this.getClass().getName(), f.getAbsolutePath());

Look at this location if the file is really created - if not, you won't be able to read.

EDIT: removed the guess with flush which was quite some nonsense

mort
-1 - You *do not* need to flush a stream before closing it. The close will do a flush. Anyway, that would not cause a `FileNotFoundException`, because the file would be created by the FileOutputStream constructor invocation.
Stephen C
That returned /test1 so I suppose it is relative to the app, which makes sense. Don't think I can access that file area from within the emulator, which is a shame
FrinkTheBrave
+1  A: 

Have you tried openfileinput("test1) instead of new FileInputStream("test1")?

plagelao
Cheers. That worked a treat, thanks. Not sure whynew FileInputStream("test1")didn't work tho as it was copied from an example
FrinkTheBrave
Documentation is error prone :PI'm glad it helped! :)
plagelao