![](/img/trans.png)
[英]JAVA application with file write/output on linux cant be read by non root user
[英]How to read/write to a file that can be accessed by a user not being root?
我想写入一个可以从文件系统访问而无需 root 的文件。
这是我的尝试:
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();
哪个写到
/data/user/0/com.example.PROJECT_NAME/files/test.txt
如果不是 root,则无法访问。
如果有可能指定一个我知道我可以访问的不同的绝对路径,例如/data/data/...
,那就太好了。
我的设备是 Google Pixel C,不幸的是它没有可写入的外部 SD 卡插槽。
在我发现在不同的 android 版本中访问外部存储的可能性有很大不同后,我选择使用存储访问框架 (SAF)。 SAF 是一个 API(自 API 级别 19 起),它为用户提供一个 UI 来浏览文件。
使用 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);
在用户选择文件后onActivityResult(...)
被调用。 现在可以通过调用 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();
}
}
}
}
现在使用此 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.