TooManyEduardos
TooManyEduardos

Reputation: 4444

Android can't find file in assets folder

I'm trying to open a .pdf within my app. The .pdf file is embedded with my app and it will be shipped within the "assets" folder (or any other folder, if that works). The file can be opened directly in Eclipse and it can be found in the finder (mac) inside the assets folder....so I know it's there.

In my code I have this:

    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 log shows the file name as "file = privacy.pdf" (my file) but the file.exists() always returns false.

Any idea on what I'm doing wrong? Thank you very much.

Upvotes: 1

Views: 4347

Answers (1)

James McCracken
James McCracken

Reputation: 15766

You can't just create a File from an asset name. You're essentially trying to create a file with a full path of "privacy.pdf". You should simply open the asset as an InputStream.

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

If you absolutely need it as a File object, you can write the InputStream to the application's files directory and use that. This code will write the asset to a file that you can then use like your question displays.

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();

Upvotes: 2

Related Questions