2016-12-27 122 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())