【问题标题】:Android can't find file in assets folderAndroid在资产文件夹中找不到文件
【发布时间】:2015-03-10 01:06:30
【问题描述】:

我正在尝试在我的应用中打开一个 .pdf。 .pdf 文件嵌入到我的应用程序中,它将在“assets”文件夹(或任何其他文件夹,如果可行的话)中提供。 该文件可以直接在 Eclipse 中打开,并且可以在 assets 文件夹内的 finder (mac) 中找到....所以我知道它在那里。

在我的代码中我有这个:

    AssetManager assetManager = getAssets();
    String[] files = null;
    try 
    {
        files = assetManager.list("");
    } 
    catch (IOException e1) 
    {
        e1.printStackTrace();
    }

    System.out.println("file = " + files[1]);
    File file = new File(files[1]);

    if (file.exists()) 
    {
        // some code to open the .pdf file
    }

Tho 日志将文件名显示为“file = privacy.pdf”(我的文件),但 file.exists() 始终返回 false。

知道我做错了什么吗? 非常感谢。

【问题讨论】:

  • 检查“同意”文件夹是否在正确的位置:click for info

标签: android


【解决方案1】:

您不能只从资产名称创建File。您实际上是在尝试创建一个完整路径为“privacy.pdf”的文件。您只需以InputStream 的形式打开资产即可。

InputStream inputStream = getAssets().open("privacy.pdf");

如果您绝对需要它作为File 对象,您可以将InputStream 写入应用程序的文件目录并使用它。此代码会将资产写入文件,然后您可以像问题显示一样使用该文件。

String filePath = context.getFilesDir() + File.separator + "privacy.pdf";
File destinationFile = new File(filePath);

FileOutputStream outputStream = new FileOutputStream(destinationFile);
InputStream inputStream = getAssets().open("privacy.pdf");
byte[] buffer = new byte[1024];
int length = 0;
while((length = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();

【讨论】:

  • 问题是我需要它作为文件,因为后来我将它用作 Uri 和路径的文件:Uri path = Uri.fromFile(file); Intent 意图 = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(路径,“应用程序/pdf”); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  • 添加了代码来演示将资产写入文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 2012-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多