Search code examples
androidfile-iogalaxy-tab

0Byte files on external usb device when not properly unmounted on Android Galaxy Tab 10.1


My application writes to an external sdcard using the Samsung adapter for the galaxy tab. When the usb device is "removed safely" then the files are all ok, however when the device is removed unsafely then all of the newly written files are 0bytes.

Here is a cut down version of the code:

    String json = "{some data to export}";

    String folderPath = Environment.getExternalStorageDirectory().toString() + File.separator + "Storages" + File.separator + "usb" + File.separator + "sda";
    File outputFile = new File(folderPath, "export.txt");

    FileWriter writer = new FileWriter(outputFile);
    BufferedWriter out = new BufferedWriter(writer);
    out.write(json);
    out.flush();
    out.close();

As you can see I am flushing and closing the file, however it looks to me like Android isn't actually bothering to flush the contents before the usb is unmounted.

The obvious solution is to tell the users to unmount safely, however we all know what users are like. So is there a way to force Android to flush the contents of the files to the sd card programmatically? (in addition to the BufferedWriter.flush / BufferedWriter.close)

The device is a Samsung Galaxy Tab 10.1 GT-P7510 running Android 3.1


Solution

  • You need to sync() your file before closing it.

      FileOutputStream fos=new FileOutputStream(someLikelyFileObject);
      BufferedOutputStream out=new BufferedOutputStream(fos);
    
      try {
        // write stuff to out
    
        out.flush();
      }
      finally {
        fos.getFD().sync();
        out.close();
      }
    

    Read more in this Android Developer Blog post.