0

I Want to get a file's location in the assets folder, I use aspose cell to work with excel files, I have a file in assets folder but cannot open this file with the following code:

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

error:

java.io.FileNotFoundException: 62.xlsx
mohammad
  • 339
  • 1
  • 3
  • 10
  • 1
    Does this answer your question? [How to access a file from asset/raw directory](https://stackoverflow.com/questions/45908648/how-to-access-a-file-from-asset-raw-directory) – fdermishin Dec 12 '20 at 09:11
  • @fdermishin no, I need assets folder path as string – mohammad Dec 12 '20 at 09:34

1 Answers1

2

You cannot get the absolute file path of a file that locates in assets folder, but you can retrieve an InputStream to read data from that file.

Solution

Copy content of the file into a temp file that locates in the cache directory, then use that temp file to pass into the constructor of Workbook class.

Step 1. Create a method that gets a temp file from a file in assets folder

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;
}

Step 2. Use that method from code.

File file = getFileFromAssets("62.xlsx");
Workbook workbook = new Workbook(file.getAbsolutePath());
Son Truong
  • 13,661
  • 5
  • 32
  • 58