1

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.

TooManyEduardos
  • 4,206
  • 7
  • 35
  • 66
  • Check that the "assents" folder is in correct location: [click for info](http://stackoverflow.com/a/24636499/3739151). – Ilia S. Jun 09 '16 at 09:10

1 Answers1

2

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();
James McCracken
  • 15,488
  • 5
  • 54
  • 62
  • The problem is that I need it as a File since later I'm using it as a file for Uri and path: Uri path = Uri.fromFile(file); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(path, "application/pdf"); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); – TooManyEduardos Jun 09 '14 at 22:12
  • added code to demonstrate writing the asset to a file. – James McCracken Jun 09 '14 at 22:18