Skip to content Skip to sidebar Skip to footer

Writing To Text File In "APPEND Mode" In Emulator-mode,

In my Android app I should store the data from user in simple text-file, that I created in the raw directory. After this, I'm trying to write file in APPEND MODE by using simple co

Solution 1:

openFileOutput will only allow you to open a private file associated with this Context's application package for writing. I'm not sure where the file you're trying to write to is located. I mean full path. You can use the code below to write to a file located anywhere (as long as you have perms). The example is using the external storage, but you should be able to modify it to write anywhere:

public Uri writeToExternalStoragePublic() {
    final String        filename        = mToolbar.GetTitle() + ".html"; 
    final String        packageName     = this.getPackageName();
    final String        folderpath      = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + packageName + "/files/";
    File                folder          = new File(folderpath);
    File                file            = null;
    FileOutputStream    fOut            = null;

    try {
        try {
            if (folder != null) {
                boolean exists = folder.exists();
                if (!exists) 
                    folder.mkdirs();                    
                file = new File(folder.toString(), filename);
                if (file != null) {
                    fOut = new FileOutputStream(file, false);
                    if (fOut != null) {
                        fOut.write(mCurrentReportHtml.getBytes());
                    }
                }
            }
        } catch (IOException e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
        return Uri.fromFile(file);
    } finally {
        if (fOut != null) {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    }
}

In the example you have given, try catching 'I0Exception`, I have a feeling you do not have permission where you are trying to write.

Have a Happy New Year.


Post a Comment for "Writing To Text File In "APPEND Mode" In Emulator-mode,"