2016-12-27 126 views
2

我想從我的資產文件夾中讀取pdf文件,但我不知道如何獲得pdf文件的路徑。 我右鍵點擊PDF文件,然後選擇「複製路徑」並粘貼enter image description here如何從資產文件夾創建文件對象?

這裏是我的代碼的另一截屏: enter image description here

這裏是我的代碼:

File file = new File("/Users/zulqarnainmustafa/Desktop/ReadPdfFile/app/src/main/assets/Introduction.pdf"); 

    if (file.exists()){ 
     Uri path = Uri.fromFile(file); 
     Intent intent = new Intent(Intent.ACTION_VIEW); 
     intent.setDataAndType(path, "application/pdf"); 
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     try { 
      this.startActivity(intent); 
     } 
     catch (ActivityNotFoundException e) { 
      Toast.makeText(this, "No application available to view PDF", Toast.LENGTH_LONG).show(); 
     } 
    }else{ 
     Toast.makeText(this, "File path not found", Toast.LENGTH_LONG).show(); 
    } 

我總是找不到文件,幫助我創建File對象或讓我知道如何獲得文件的確切路徑我也試過file:///android_asset/Introduction.pdf但沒有成功。我也用Image.png嘗試過,但從未獲得file.exists()成功。我正在使用Mac版的Android studio。謝謝

+2

http://stackoverflow.com/questions/9544737/read-file-from-assets的可能重複嘗試 –

+0

我想創建'文件'在上面一個創建InputStream – Zulqarnain

+0

http://stackoverflow.com/questions/17085574/read-a-pdf-file-from-assets-folder檢查此,這是類似於你想要實現 –

回答

2

從資產獲取輸入流並將其轉換爲文件對象。

File f = new File(getCacheDir()+"/Introduction.pdf"); 
if (!f.exists()) 
try { 

    InputStream is = getAssets().open("Introduction.pdf"); 
    byte[] buffer = new byte[1024]; 
    is.read(buffer); 
    is.close(); 


    FileOutputStream fos = new FileOutputStream(f); 
    fos.write(buffer); 
    fos.close(); 
} catch (Exception e) { throw new RuntimeException(e); } 
0

你可以試試這個代碼

AssetManager am = getAssets(); 
InputStream inputStream = am.open("Indroduction.pdf"); 
File file = createFileFromInputStream(inputStream); 

private File createFileFromInputStream(InputStream inputStream) { 

    try{ 
     File f = new File("new FilePath"); 
     OutputStream outputStream = new FileOutputStream(f); 
     byte buffer[] = new byte[1024]; 
     int length = 0; 

     while((length=inputStream.read(buffer)) > 0) { 
     outputStream.write(buffer,0,length); 
     } 

     outputStream.close(); 
     inputStream.close(); 

     return f; 
    }catch (IOException e) { 
     //Logging exception 
    } 

    return null; 
} 

然後用

File file = new File("new file path"); 

if (file.exists())