[英]How to read/write to a file that can be accessed by a user not being root?
I would like to write to a file that I can access from the file system without being root.我想写入一个可以从文件系统访问而无需 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.如果不是 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/...
.如果有可能指定一个我知道我可以访问的不同的绝对路径,例如
/data/data/...
,那就太好了。
My device is a Google Pixel C which unfortunately has no external SD-Card slot to write to.我的设备是 Google Pixel C,不幸的是它没有可写入的外部 SD 卡插槽。
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).在我发现在不同的 android 版本中访问外部存储的可能性有很大不同后,我选择使用存储访问框架 (SAF)。 The SAF is an API (since API level 19), that offers the user a UI to browse through files.
SAF 是一个 API(自 API 级别 19 起),它为用户提供一个 UI 来浏览文件。
Using an Intent, an UI pops up which lets the user create a file or choose an existing one:使用 Intent,会弹出一个 UI,让用户创建文件或选择现有文件:
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.在用户选择文件后
onActivityResult(...)
被调用。 Now it is possible to get the URI of the file by calling resultData.getData();现在可以通过调用 resultData.getData() 来获取文件的 URI;
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:现在使用此 URI 写入文件:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.