Writing to an External File on Android --- File Doesn't Register, But Java Can Read

454 views Asked by At

I'm trying to write to an external txt (or csv) file for Android. I can run an app, close it, and run it again, and readData() will read back to my log what I've stored. However, the dirFile (file directory) appears nowhere within my Android files (even if I connect it to a computer and search).

Something interesting, though: if I clear my log (similar to a list of print statements shown within Eclipse) and disconnect my phone from my computer, then reconnect it, the log reappears with everything I've ever written to my file (even if I later overwrote it)...yet the app isn't even running!

Here is my code. Please help me understand why I cannot find my file!

(Note: I've tried appending a "myFile.txt" extension to the directory, but it just causes an EISDIR exception.)

public void writeData(String dirName){

    try
    {
        File root = new File(getExternalFilesDir(null), dirName);

        // Writes to file
        //
        // The "true" argument allows the file to be appended. Without this argument (just root),
        // the file will be overwritten (even though we later call append) rather than appended to.

        FileWriter writer = new FileWriter(root, true);
        writer.append("Append This Text\n");
        writer.flush();
        writer.close();

        // Checks if we actually wrote to file by reading it back in (appears in Log)

        //readData(dirName);
    }
    catch(Exception e)
    {
         Log.v("2222", "2222 ERROR: " + e.getMessage());
    }
}

If you're interested, here's the function I wrote to read in the data:

public void readData(String dirName){

    try
    {
        File root = new File(getExternalFilesDir(null), dirName);

        // Checks to see if we are actually writing to file by reading in the file

        BufferedReader reader = new BufferedReader(new FileReader(root));
        try {
            String s = reader.readLine();
            while (s != null) {
                Log.v("2222", "2222 READ: " + s);
                s = reader.readLine();
            }
        }
        catch(Exception e) {
             Log.v("2222", "2222 ERROR: " + e.getMessage());
        }
        finally {
            reader.close();
        }
    }
    catch(Exception e) {
         Log.v("2222", "2222 ERROR: " + e.getMessage());
    }
}

Thanks!

2

There are 2 answers

0
CommonsWare On

even if I connect it to a computer and search

if I clear my log (similar to a list of print statements shown within Eclipse) and disconnect my phone from my computer, then reconnect it, the log reappears with everything I've ever written to my file (even if I later overwrote it).

What you are seeing on your computer is what is indexed by MediaStore, and possibly a subset of those, depending upon whether your computer caches information it gets from the device in terms of "directory" contents.

To help ensure that MediaStore indexes your file promptly:

  1. Use a FileOutputStream (optionally wrapped in an OutputStreamWriter), not a FileWriter

  2. Call flush(), getFD().sync(), and close() on the FileOutputStream, instead of calling flush() and close() on the FileWriter (sync() will ensure the bytes are written to disk before continuing)

  3. Use MediaScannerConnection and scanFile() to tell MediaStore to index your file

You can then use whatever sort of "reload" or "refresh" or whatever option is in your desktop OS's file manager, and your file should show up.

This blog post has more on all of this.

0
DineshkumarBalan On
public void create(){

folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),"video");
    boolean success = true;
    if (!folder.exists()) {
    success=folder.mkdirs();

    }
    if (success) {
                    readfile();
    } else {
        System.out.println("failed");
    }
}

The above code will be used to crete the directory in th emobile at desired path

private void readfile() {
// TODO Auto-generated method stub
AssetManager assetManager = getResources().getAssets();
String[] files = null;
try {
    files = assetManager.list("clipart");
} catch (Exception e) {
    Log.e("read clipart ERROR", e.toString());
    e.printStackTrace();
}
for(String filename : files) {
    System.out.println("File name => "+filename);
    InputStream in = null;
    OutputStream out = null;
    try {
      in = assetManager.open("clipart/" + filename);
      out = new FileOutputStream(folder + "/" + filename);
      copyFile(in, out);
      in.close();
      in = null;
      out.flush();
      out.close();
      out = null;
    } catch(Exception e) {
        Log.e("copy clipart ERROR", e.toString());
        e.printStackTrace();
    }       
}}private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
  out.write(buffer, 0, read);
}}

this is my code used to write file in internal memory from the assets folder in project. This code can read all type(extension) of file from asset folder to mobile.

Don't forget to add permission in manifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

and call the above function by

readfile();//this call the function to read and write the file

I hope this may help you. Thank you.