2
File file = new File("android.resource://com.baltech.PdfReader/assets/raw/"+filename);

                    if (file.exists()) {
                    Uri targetUri = Uri.fromFile(file);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(targetUri, "application/pdf");
                        try {
                            startActivity(intent);
                        } 
                        catch (ActivityNotFoundException e) {
                            Toast.makeText(PdfReaderActivity.this, "No Application Available to View PDF", Toast.LENGTH_SHORT).show();
                        }

我想阅读资产文件夹中的 .pdf 文件。我必须在文件名中给出什么路径。请帮忙。谢谢

4

3 回答 3

3

我不确定你是否已经得到了这个答案,看起来很老了,但这对我有用。

//you need to copy the input stream to a new file, so store it elsewhere
//this stores it to the sdcard in a new folder "MyApp"
String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyApp/solicitation_form.pdf";

AssetManager assetManager = getAssets();

try {
    InputStream pdfFileStream = assetManager.open("solicitation_form.pdf");
    CreateFileFromInputStream(pdfFileStream, filename);

} catch (IOException e1) {
    e1.printStackTrace();
}

File pdfFile = new File(filename); 

CreateFileFromInputStream 函数如下

public void CreateFileFromInputStream(InputStream inStream, String path) throws IOException {
    // write the inputStream to a FileOutputStream
    OutputStream out = new FileOutputStream(new File(path));

    int read = 0;
    byte[] bytes = new byte[1024];

    while ((read = inStream.read(bytes)) != -1) {
        out.write(bytes, 0, read);
    }

    inStream.close();
    out.flush();
    out.close();

}

真的希望这可以帮助其他阅读本文的人。

于 2013-03-07T21:20:08.930 回答
2
File file = new File("file:///android_asset/raw/"+filename);

用下面替换上面的行并尝试..

File file = new File("android.resource://com.com.com/raw/"+filename);

并放置您的 PDF 文件原始文件夹而不是资产。还将 com.com.com 更改为您的包名称。

于 2012-04-13T08:08:06.443 回答
1

由于资产文件存储在 apk 文件中,因此资产文件夹没有绝对路径。您可以使用一种解决方法来创建用作缓冲区的新文件。

您应该使用 AssetManager:

AssetManager mngr = getAssets();
InputStream ip = mngr.open(<filename in the assets folder>);
File assetFile = createFileFromInputStream(ip);


private File createFileFromInputStream(InputStream ip);

try{
   File f=new File(<filename>);
   OutputStream out=new FileOutputStream(f);
   byte buf[]=new byte[1024];
   int len;
   while((len=inputStream.read(buf))>0)
     out.write(buf,0,len);
  out.close();
  inputStream.close();

 }catch (IOException e){}
}
}
于 2012-04-13T08:14:01.773 回答