2017-08-12 1 views
0

私はsdcardからpdfを選択してバイト配列に変換する必要があります。私はそれを見せたくありません。私は多くを検索しましたが、この質問に対する答えはありませんでした。sdcardからpdfを選択し、アンドロイドスタジオのバイト配列に変換してください

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 

    if (requestCode == SELECT_MAGAZINE_FILE && resultCode == RESULT_OK && data != null) { 
     // Let's read picked image data - its URI 
     Uri uri = data.getData(); 
     System.out.println(uri); 
     System.out.println(uri.getPath()); 
     File file = new File(uri.getPath()); 
      //init array with file length 
     byte[] bytesArray = new byte[(int) file.length()]; 

     FileInputStream fis = null; 
     try { 
      fis = new FileInputStream(file); 
      fis.read(bytesArray); //read file into bytes[] 
      fis.close(); 

      System.out.println(bytesArray); 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 
} 

と、私はこのエラーを得た:

せいぜい
java.io.FileNotFoundException: /document/primary:myfile.pdf: open failed: ENOENT (No such file or directory) 

答えて

0

ありがとうございましたhttps://stackoverflow.com/users/115145/commonswareあなたのお手伝いをします。

私のコードをこれに変更して動作します。 AsyncTaskを使用する方がよいでしょう。

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 

    if (requestCode == SELECT_MAGAZINE_FILE && resultCode == RESULT_OK && data != null) { 
     // Let's read picked image data - its URI 
     Uri uri = data.getData(); 
     File file = new File(uri.getPath()); 

     try { 
      InputStream is = getActivity().getContentResolver().openInputStream(uri); 
      byte[] bytesArray = new byte[is.available()]; 
      is.read(bytesArray); 

      //write to sdcard 
      /* 
      File myPdf=new File(Environment.getExternalStorageDirectory(), "myPdf.pdf"); 
      FileOutputStream fos=new FileOutputStream(myPdf.getPath()); 
      fos.write(bytesArray); 
      fos.close();*/ 

      System.out.println(fileString); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
1

onActivityResult()に配信されてUrifileスキームを持って発生した場合、あなたのコードは動作します。あなたはしません。それはcontentスキームを持っています。 OutOfMemoryErrorのコードでは、コードがbyte[]の割り当てに失敗するため、コードも多く失敗します。 PDFファイルはかなり大きくすることができます。

したがって、PDFファイル全体をbyte[]に読み込む代わりに、他の解決策を見つけることはまずありません。信頼性が低く、修正するために行うことはできません。

最終的にUriで示されるコンテンツにInputStreamを取得するには、ContentResolveropenInputStream()を使用します。

そして、長期的には、このI/Oをバックグラウンドスレッドに移動する必要があります。現在は、データを読み込むためにUIをフリーズします。

ContentResolverUriの値を使用し、スレッドを使用することは、Androidアプリの開発ではまともな本やコースでカバーされています。

関連する問題