2012-05-07 41 views
0

我想從我的原始文件夾中傳遞一個PDF從SD卡上打開它與默認意圖。從資產傳遞PDF到SD卡

當我打開它時,據說我的PDF損壞了。因爲我不太瞭解溪流的工作原理,所以我認爲這個問題會在那裏出現。

final String extStorageDirectory = Environment 
         .getExternalStorageDirectory().toString(); 
       final String festivalDirectory_path = extStorageDirectory 
         + Constants.PDF_STORAGE_PATH; 
       File pdfOutputFile = new File(festivalDirectory_path, "/"); 
       if (pdfOutputFile.exists() == false) { 
        pdfOutputFile.mkdirs(); 
       } 
       File pdfFile = new File(pdfOutputFile, nameOfThePdf); 

       try { 
        InputStream in = getResources().openRawResource(R.raw.blablublo); 

        FileOutputStream out = new FileOutputStream(pdfFile); 
        byte[] buffer = new byte[1024]; 
        int bufferLength = 0; 
        while ((bufferLength = in.read(buffer)) > 0) { 
         out.write(buffer, 0, bufferLength); 
        } 
        out.close(); 
       } catch (Exception e) { 
        Log.e("tag", e.getMessage()); 
       } 
       Uri path = Uri.fromFile(pdfFile); 
//    Uri path = Uri.parse(Constants.SPLASH_URI + R.raw.cartecannotpdf); 
       Intent intent = new Intent(Intent.ACTION_VIEW); 
       intent.setDataAndType(path, "application/pdf"); 
       intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       startActivity(intent); 

希望有人能幫助我!

THX

雷諾

+0

您不是_copying_文件。看看http://stackoverflow.com/a/4530294/1321873 – Rajesh

+0

thx,我看看這個鏈接,並因此修改我的代碼,但我必須錯過其他 –

+0

現在是什麼問題?嘗試隔離問題 - 檢查是否可以讀取複製的文件(例如,通過下載到您的計算機)。 – Rajesh

回答

0

嗯,它看起來像你的解決方案是完成了一半。

InputStream inputStream = assetManager.open("cartecanotpdf.pdf"); - 創建一個流,您可以使用它讀取資產文件夾中PDF文件的所有數據。

File file = new File(dir, "cartecannotpdf.pdf"); - 這只是創建一個指向SDCARD上文件所在位置的鏈接。

您缺少的Teh部分實際上是將輸入流中的字節複製到輸出流。目前,SDCARD上的文件不存在,或者它只是一個空殼(沒有任何數據),所以你的意圖會抱怨它已經損壞。

這是一個QA,它有一個完整的解決方案。 How to copy files from 'assets' folder to sdcard?

編輯:另外,我不確定您是否需要將文件放在您的資產文件夾中,或者如果您可以將它保留在RAW文件夾中。我一直在使用我的資產文件夾中的文件。確保你在調用assetManager.open(...)時確實獲得了一個文件

+0

好的抱歉,延遲,我試圖修改我的代碼,因爲你們都說,它仍然無法正常工作。以爲我認爲我現在已經很好地填充了SD卡文件。我沒有看到其他的方法來讀取一個PDF比這個 –

+0

1)嘗試調用out.flush();'out.close()之前'2)什麼是原始和複製PDF文件的大小? – Gophermofur

+0

嘗試更改'FileOutputStream out = new FileOutputStream(pdfFile);'OutputStream out = new FileOutputStream(pdfFile);' – Gophermofur