【问题标题】:Get file location in assets folder [duplicate]获取资产文件夹中的文件位置[重复]
【发布时间】:2020-12-12 09:09:21
【问题描述】:

我想在资产文件夹中获取文件的位置, 我使用 aspose 单元处理 excel 文件, 我在 assets 文件夹中有一个文件,但无法使用以下代码打开此文件:

Workbook workbook = new Workbook("/assets/62.xlsx");

错误:

java.io.FileNotFoundException: 62.xlsx

【问题讨论】:

标签: java android


【解决方案1】:

您无法获取位于assets 文件夹中的文件的绝对文件路径,但您可以检索InputStream 以从该文件中读取数据。

解决方案

将文件内容复制到缓存目录中的临时文件中,然后使用该临时文件传递给Workbook类的构造函数。

第 1 步。创建一个从assets文件夹中的文件中获取临时文件的方法

private File getFileFromAssets(String fileName) {
    File file = new File(getCacheDir(), fileName);
    FileOutputStream fos = null;
    InputStream is = null;
    try {
        fos = new FileOutputStream(file);
        is = getAssets().open(fileName);
        byte[] buffer = new byte[1024]; // 1MB buffer
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            fos.write(buffer, 0, bytesRead);
        }
        fos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }

            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file.length() > 0 ? file : null;
}

第 2 步。在代码中使用该方法。

File file = getFileFromAssets("62.xlsx");
Workbook workbook = new Workbook(file.getAbsolutePath());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2014-03-10
    • 2018-09-20
    相关资源
    最近更新 更多