繁体   English   中英

onActivityResult中的FileNotFoundException

[英]FileNotFoundException in onActivityResult

我正在尝试仅浏览两种文件类型:图像或pdf。

来源如下:

String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
            myPermissions =new MyPermissions(TestDialog.this, 0, permissions);
            MyPermissions.EventHandler permHandler = new MyPermissions.EventHandler() {
                @Override
                public void handle() {

                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    intent.setType("application/pdf");
                    intent.setType("image/jpeg");
                    startActivityForResult(intent, 0);
                }
            };

            myPermissions.doIfHasPermissions(permHandler);

这是我的onActivityResult源:

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        String url = data.getData().getPath();
        File myFile = new File(url);
        Log.e("base64 ", getStringFile(myFile));


    }
    super.onActivityResult(requestCode, resultCode, data);
}

public String getStringFile(File f) {
    InputStream inputStream = null;
    String encodedFile = "", lastVal;
    try {
        inputStream = new FileInputStream(f.getAbsolutePath());

        byte[] buffer = new byte[10240];//specify the size to allow
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT);

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            output64.write(buffer, 0, bytesRead);
        }
        output64.close();
        encodedFile = output.toString();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    lastVal = encodedFile;
    return lastVal;
}

我想将所选文件转换为Base64,但得到FileNotFoundException 有人知道我在做什么错吗?

我尝试仅浏览两种类型的文件,图像或pdf

您的代码与文件无关。 它使用ACTION_GET_CONTENT ,它允许用户选择内容。

String url = data.getData().getPath();

除非Uri有一个file方案,否则此行是无用的。 它很可能具有content计划。

停止使用FileFileInputStream 而是从ContentResolver (从getContentResolver() )及其openInputStream()方法获取InputStream 您可以传入Uri ,无论Uri方案是file还是content ,您都将获得InputStream

还要注意,您的应用可能会因OutOfMemoryError崩溃,但文件很小,因为您没有足够的堆空间来执行此转换。

看一下

Uri uri = data.getData(); 

然后尝试记录uri.toString()的值。

您将看到它以“ content // ....”开头。

不要尝试查找文件。

代替FileInputStream使用InputStream。

InputStream inputStream = getContentResolver().openInputStream(uri);

暂无
暂无

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

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