简体   繁体   English

使用 FileOutputStream 编辑/修改 Uri 引用文件 Android

[英]Edit/Modify Uri referenced file using FileOutputStream Android

I am using ActivityResultLauncher to fetch uri of a file.我正在使用 ActivityResultLauncher 来获取文件的 uri。 Now I want to modify that file using fileoutputStream but can't, since fileoutputstream need path string.现在我想使用 fileoutputStream 修改该文件但不能,因为 fileoutputstream 需要路径字符串。 Here is a code that I am using to get File Uri:这是我用来获取文件 URI 的代码:

ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    // There are no request codes
                    Intent data = result.getData();
                    Uri uri = data.getData();//this gets me URI
                    

                }
            }
      });

public void openFileChooser()
{
    Intent data = new Intent(Intent.ACTION_GET_CONTENT);
    data.addCategory(Intent.CATEGORY_OPENABLE);
    data.setType("*/*");
    data = Intent.createChooser(data, "Choose a file");
    Intent intent = Intent.createChooser(data, "Choose a file");
    someActivityResultLauncher.launch(intent);
}

The code works perfect for picking and reading file.该代码非常适合选择和读取文件。 But I am not able to use below mentioned function to write same file using:但我无法使用下面提到的 function 来编写相同的文件:

static void writeToFile(String path,String data,Context context) {
    try {
        FileOutputStream output = null;
        output = new FileOutputStream(path, false);
        output.write(data.getBytes());
        output.close();
        Toast.makeText(getApplicationContext(),"SAVED",Toast.LENGTH_LONG).show();
    }
    catch (IOException e) {
        Toast.makeText(getApplicationContext(),"File write failed: " + e.toString(),Toast.LENGTH_LONG).show();
    }
}

I have tried uri.getPath() but it is returning /document/msf:21.我试过 uri.getPath() 但它返回 /document/msf:21。 That is some complicated uri string and can't be used as file path.那是一些复杂的 uri 字符串,不能用作文件路径。 I have also been trying to use realPath functions mentioned in stackflow and other forums but do not find it working (they may work but they are depending upon API levels that making them not reliable).我也一直在尝试使用 stackflow 和其他论坛中提到的 realPath 函数,但没有发现它有效(它们可能有效,但它们取决于 API 级别,这使得它们不可靠)。 So, what actually want to ask:那么,其实想问的是:

1- Is there any other way to pick file to get actual path? 1-还有其他方法可以选择文件以获取实际路径吗?

2- If there is no way to pick path, how can I write to File using direct Uri? 2-如果无法选择路径,我如何使用直接 Uri 写入文件? and not using getpath or path string.并且不使用 getpath 或路径字符串。

3- Is there a way to use fileoutstream with Uri in this scenario where Uri is only available? 3- 在这种只有 Uri 可用的情况下,有没有办法将 fileoutstream 与 Uri 一起使用?

Thanks谢谢

OutputStream os = getContentResolver().openOutputStream(data.getData());

You need to pass it through input stream amd buffer reader with output stream.您需要通过输入 stream amd 缓冲区读取器和 output stream 传递它。

Try this on start intent在开始意图上试试这个

Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf");
intent.putExtra(Intent.EXTRA_TITLE, "JWI.pdf");
startActivityForResult(intent, CREATE_FILE);

Try this on activity result在活动结果上试试这个

try {
uri = _data.getData();
muri = uri.toString();
t.edit().putString("Uri", muri).commit();
        
final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION | 
Intent.FLAG_GRANT_WRITE_URI_PERMISSION; 
getContentResolver().takePersistableUriPermission(uri, takeFlags);
        
        
DocumentFile doc = DocumentFile.fromSingleUri(this, uri);
boolean doo = doc.exists();
if (!doo) {
DocumentFile f = doc.createFile("pdf/plain", "JAMZ.pdf");}
        
ContentResolver cr = getContentResolver(); OutputStream output =
cr.openOutputStream(uri); 
java.io.InputStream asset = getAssets().open("JWI.pdf");


final byte[] buffer = new byte[1024];

int size;

while ((size = asset.read(buffer)) != -1) {

output.write(buffer, 0, size);

}

asset.close();

output.close();
} catch (Exception e) {}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM