簡體   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