I would like to write to a file that I can access from the file system without being root.
This is my attempt:
FileOutputStream fos = null;
final String FILE_NAME = "test.txt";
fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
fos.write("test".getBytes());
// Display path of file written to
Toast.makeText(this, "Saved to" + getFilesDir() + "/" + FILE_NAME, Toast.LENGTH_LONG).show();
Which writes to
/data/user/0/com.example.PROJECT_NAME/files/test.txt
which is not accessible without being root.
It would be good if there is a possibility to specify a different, absolute path which I know I can access, such as /data/data/...
.
My device is a Google Pixel C which unfortunately has no external SD-Card slot to write to.
After I figured out that the possibilities of accessing external storage differ quite a lot in different android versions, I chose to go with the Storage Access Framework (SAF). The SAF is an API (since API level 19), that offers the user a UI to browse through files.
Using an Intent, an UI pops up which lets the user create a file or choose an existing one:
private static final int CREATE_REQUEST_CODE = 40;
private Uri mFileLocation = null;
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain"); // specify file type
intent.putExtra(Intent.EXTRA_TITLE, "newfile.txt"); // default name for file
startActivityForResult(intent, CREATE_REQUEST_CODE);
After the user chose a file onActivityResult(...)
gets called. Now it is possible to get the URI of the file by calling resultData.getData();
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if (resultCode == Activity.RESULT_OK)
{
if (requestCode == CREATE_REQUEST_CODE)
{
if (resultData != null) {
mFileLocation = resultData.getData();
}
}
}
}
Now use this URI to write to the file:
private void writeFileContent(Uri uri, String contentToWrite)
{
try
{
ParcelFileDescriptor pfd = this.getContentResolver().openFileDescriptor(uri, "w"); // or 'wa' to append
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write(contentToWrite.getBytes());
fileOutputStream.close();
pfd.close();
} catch (IOException e) {
e.printStackTrace();
}
}