Java 如何读取/写入非root用户可以访问的文件?

Java 如何读取/写入非root用户可以访问的文件?,java,android,file,storage-access-framework,google-pixel,Java,Android,File,Storage Access Framework,Google Pixel,我想写一个文件,我可以从文件系统访问,而不是根 这是我的尝试: 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" + getF

我想写一个文件,我可以从文件系统访问,而不是根

这是我的尝试:

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

如果不是根目录,则无法访问

如果有可能指定一个我知道可以访问的不同的绝对路径,例如
/data/data/…
,那就太好了


我的设备是Google Pixel C,不幸的是,它没有外部SD卡插槽可供写入。

在我发现在不同的android版本中访问外部存储的可能性有很大差异后,我选择使用存储访问框架(SAF)。SAF是一个API(自API级别19以来),它为用户提供了一个浏览文件的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

现在使用此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();
    }
}

“如果不是root用户,则无法访问”--您的应用程序可以访问它,而不是root用户。其他应用程序或非root用户无法访问它。“如果有可能指定一个我知道可以访问的不同的绝对路径,例如/data/data/…”--/data/data/…就是您要写的地方,也就是说。应用程序看到的路径可能与您在Studio的设备文件资源管理器等工具中看到的路径不完全匹配。“我的设备是Google Pixel C,不幸的是,它没有外部SD卡插槽可供写入。”--我同意Pixel C缺少用于存储的内置选项。不过,它确实有,欢迎您在Android 9及更高版本上使用,在Android 10及更高版本上使用。谢谢!这正是帮助我的。现在我将使用SAF(存储访问框架)解决我的问题。一个医生帮了我。
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();
    }
}