2017-11-14 15 views
-1

私は2つのファイルタイプ(画像またはpdf)のみを参照しようとしています。ここでonActivityResultのFileNotFoundException

がソースである:ここでは

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を取得します。誰かが私が間違って何を考えているか?

答えて

1

)がuri.toString(の値をログに記録しようと次に

Uri uri = data.getData(); 

を見てください。

"content // ...."で始まることがわかります。

ファイルを検索しないでください。

FileInputStreamの代わりにInputStreamを使用します。

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

ありがとうございます.Greenappsは完璧です – BekaKK

1

私は2つだけの種類のファイル、画像やPDF

を閲覧しようとするあなたのコードは、ファイルとはあまり関係ありません。ユーザーがコンテンツを選択できるようにするACTION_GET_CONTENTを使用します。 Urifileのスキームを持っていない限り

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

この行は、無駄です。おそらく、それはcontentというスキームを持っています。

FileFileInputStreamを使用して停止します。代わりに、ContentResolvergetContentResolver())とそのopenInputStream()メソッドからInputStreamを取得します。 Uriを渡すことができ、Uriスキームがfilecontentかどうかにかかわらず、InputStreamが得られます。

この変換を実行するのに十分なヒープスペースがないため、あなたのアプリはかなり小さいファイルを除いて、OutOfMemoryErrorでクラッシュする可能性があります。

関連する問題