【问题标题】:Android: how do I create File object from asset file?Android:如何从资产文件创建 File 对象?
【发布时间】:2012-05-11 06:35:27
【问题描述】:

我在资产文件夹中有一个文本文件,我需要将其转换为 File 对象(而不是 InputStream)。当我尝试这个时,我得到“没有这样的文件”异常:

String path = "file:///android_asset/datafile.txt";
URL url = new URL(path);
File file = new File(url.toURI());  // Get exception here

我可以修改它以使其正常工作吗?

顺便说一句,我有点尝试“通过示例编写代码”,查看我项目中其他地方引用 assets 文件夹中 HTML 文件的以下代码

public static Dialog doDialog(final Context context) {
WebView wv = new WebView(context);      
wv.loadUrl("file:///android_asset/help/index.html");

我承认我并不完全理解上述机制,所以我试图做的事情可能行不通。

谢谢!

【问题讨论】:

  • 为什么要将其读入 File 对象?我相信您需要从资产中获取数据作为 InputStream 并将其作为指向物理位置的 outputStream 写出。然后您可以将其作为 File 对象打开。 stackoverflow.com/questions/4447477/…
  • 我试图避免复制资产文件,但如果一切都失败了,我会这样做。我需要 File 的原因是它被用作我无权访问其代码的 ctor 中的参数,这是该类存在的唯一 ctor。
  • 啊,有道理。也许:将副本复制到 SDCARD 上,将其传递给构造函数,并在完成后将其删除?如果文件相同并且您始终将其保存到 SDCARD 上的相同位置,则您只会制作 1 个副本(它只会覆盖以前的版本)。

标签: android file assets


【解决方案1】:

您无法直接从资产中获取File 对象,因为资产未存储为文件。您需要将资产复制到文件中,然后在您的副本中获取 File 对象。

【讨论】:

  • 是的,那你怎么做呢?
  • @MarkMolina:见其他答案。它几乎只是标准的 Java I/O,在 AssetManager 上使用 open() 方法中的 InputStream,然后将数据从 InputStream 复制到 OutputStream 以获得所需文件。
【解决方案2】:

您不能直接从资产中获取 File 对象。

首先,使用 AssetManager#open 从您的资产中获取一个 inputStream

然后复制输入流:

    public static void writeBytesToFile(InputStream is, File file) throws IOException{
    FileOutputStream fos = null;
    try {   
        byte[] data = new byte[2048];
        int nbread = 0;
        fos = new FileOutputStream(file);
        while((nbread=is.read(data))>-1){
            fos.write(data,0,nbread);               
        }
    }
    catch (Exception ex) {
        logger.error("Exception",ex);
    }
    finally{
        if (fos!=null){
            fos.close();
        }
    }
}

【讨论】:

    【解决方案3】:

    代码中缺少此函数。 @wadali

    private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
          out.write(buffer, 0, read);
        }
    }
    

    来源:https://stackoverflow.com/a/4530294/4933464

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多