Basically I have right clicked on my project name and successfully created a new folder called pdfs. I want to pre load some pdf files in here so how would I call this path/some
Your new folder will be completely ignored by the builders. It will not be packaged with your app and copied onto any emulator or device. If you want to package data with your app, you need to use the raw or assets folders. The latter allows subfolders, so you could move your pdfs folder there.
Here's some code that will move files from assets/pdfs
to files/pdfs
under your app's designated external directory.
final static String TAG = "MainActivity";
final static int BUFF_SIZE = 2048;
private void copyPdfs() {
AssetManager assetManager = getAssets();
String[] pdfs = null;
try {
pdfs = assetManager.list("pdfs");
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Unable to get list of PDFs!");
}
File pdfDir = new File(getExternalFilesDir(null), "pdfs");
if (!pdfDir.exists()) {
Log.d(TAG, "Creating directory " + pdfDir.getAbsolutePath());
pdfDir.mkdirs();
}
for (String pdf : pdfs) {
Log.d(TAG, "Copying " + pdf);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("pdfs" + File.separator + pdf);
out = new FileOutputStream(new File(pdfDir, pdf));
copyPdf(in, out);
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Unable to copy PDF!");
}
}
}
private void copyPdf(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[BUFF_SIZE];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1)
out.write(buffer, 0, bytesRead);
out.flush();
}
Its better to place them in assets/ folder, that way you will be able to access them with AssetManager. Something like this
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "name_of_pdf_file.pdf");
try
{
in = assetManager.open("name_of_pdf_file.pdf");
in.close();
in = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
If you move your PDFs into assets/
, you can use AssetManager
to retrieve an InputStream
for them.
If your objective is to display them in a third-party PDF viewer -- as your code would suggest -- then you can:
Copy the PDF from the asset into external storage, in which case the rest of your code would work, or
Copy the PDF from the asset into internal storage, then use FileProvider
to publish it for the PDF viewer, or
Use my StreamProvider to publish the PDF to the viewer app directly from assets
Coverage of FileProvider
can be found in the Android documentation. My StreamProvider
is based on Google's FileProvider
and works similarly.