Create file from assets and get its path - android

I want to display a PDF stored in the assets folder using an external library. This library requires a path to a file.
I read that the pdf stored in the assets folder is not stored as a file. What I need is
Read the pdf-file from the assets into a (temporary) file object
get the path of that object for the external pdf-viewer-library
What I got so far is the following:
stream = getAssets().open("excerpt.pdf");
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
I'm not really sure what to do next unfortunately...
EDIT:
I tried the following code:
private void copyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String dirout= Environment.getExternalStorageDirectory().getAbsolutePath() + "/X/Y/Z/" ;
File outFile = new File(dirout, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
...
I am getting an exception in "out = new FileOutputStream(outFile);" (no such file or directory). I thought the code create a file there?

Does the directory exists?
If not, it will send an IOException.
Just to make sure, try this approach:
final File directory = new File("/sdcard/X/Y/Z/");
if (!directory.exists()) {
directory.mkdirs();
}
It will create the parent directories if they don't exist. If they exist, it will return false and it will NOT delete the content in it. After this, just continue the same way you were doing it.
File outFile = new File(directory, filename);
Don't forget to add the permissions to your AndroidManifest!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Copy the file to a public location that other applications can access using a process similar to that described in this question.
Keep a reference to the external file you created for launching your Intent(Intent.ACTION_VIEW).
Build an Intent to view your pdf, ex:
public void viewPdf(File YOUR_PUBLIC_FILE_FROM_STEP_1) {
PackageManager packageManager = getPackageManager();
Intent viewPdf = new Intent(Intent.ACTION_VIEW);
viewPdf.setType("application/pdf");
List<ResolveInfo> list =packageManager.queryIntentActivities(viewPdf,PackageManager.MATCH_DEFAULT_ONLY);
// Check available PDF viewers on device
if (list.size() > 0) {
Intent from_external_app = new Intent(Intent.ACTION_VIEW);
from_external_app.setDataAndType(Uri.fromFile(YOUR_PUBLIC_FILE_FROM_STEP_1),
"application/pdf");
from_external_app.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(from_external_app);
}

Related

Android: open failed: ENOENT No such file or directory

I know have many question like my question. But It is different. I copy file from folder A to folder B in EXTERNAL_STORAGE use mothod below:
public static String copyFile(String path) {
String fileToName = String.valueOf(System.currentTimeMillis());
File pathFrom = new File(path);
File pathTo = new File(Environment.getExternalStorageDirectory() + "/.noname");
File file = new File(pathTo, fileToName + ".bak");
while (file.exists()) {
fileToName = String.valueOf(System.currentTimeMillis());
file = new File(pathTo, fileToName + ".bak");
}
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(pathFrom);
out = new FileOutputStream(file);
byte[] data = new byte[in.available()];
in.read(data);
out.write(data);
in.close();
out.close();
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return file.getPath();
}
The path param is: "/storage/emulated/0/Download/image_preview.jpg".
When execute this method I got an error: /storage/emulated/0/Download/tree_leaves_sunlight.jpg: open failed: ENOENT (No such file or directory).
Folder .noname have exists.
Is there any suggestion for my problem?
**UPDATE: This file I opening with ImageView. When I not open I can copy. But When I opening I got this error.
PS: I preview the image inImageView. And there have a Button copy image. When click to Button execute method copy this image to other folder.
When you create the File object for the parent directory
File pathTo = new File(Environment.getExternalStorageDirectory() + "/.noname")
Don't forget to actually create this folder
pathTo.mkdirs();
Also try to open file you're trying to copy in the gallery. It can be damaged and Android just can't open it.

Unable to write to external SD Card in Android

I am trying to write files in the external SD card folder. Even after having set the required permission in the manifest file, I am unable to write on the external SD card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Code:
String path = "/mnt/extsd/nit.txt";
File myFile = new File(path);
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
}
try {
FileOutputStream fostream = new FileOutputStream(myFile);
OutputStreamWriter oswriter = new OutputStreamWriter(fostream);
BufferedWriter bwriter = new BufferedWriter(oswriter);
bwriter.write("Hi welcome ");
bwriter.newLine();
bwriter.close();
oswriter.close();
fostream.close();
txtText.setText("success");
} catch(Exception e)
{
txtText.setText("Failed-" + e.getMessage());
e.printStackTrace();
}
On the other hand when I use ES File Explorer and try to create a file, it creates it without any issues.
Don't use the absolute path String path = "/mnt/extsd/nit.txt"; because you never know about android device being used by users. Rather you can get the external storage directory path by using Environment.getExternalStorageDirectory().toString().
You should be able to call Environment.getExternalStorageDirectory() to get the root path to the SD card and use that to create a FileOutputStream. From there, just use the standard java.io routines.
File log = new File(Environment.getExternalStorageDirectory(), "your_file_name.txt");
try {
out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), false));
out.write("any data");
} catch (Exception e) {
}
And don't forget to close the streams.
First check sd-card is available or not.
String state = Environment.getExternalStorageState();
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
if (Environment.MEDIA_MOUNTED.equals(state))
{
File folder = folder = new File(extStorageDirectory, "FolderName");
if(!folder.exists())
{
folder.mkdir();//making folder
}
File file = new File(folder,"Filename");//making file
}
Please try this code, it work in my application.

Android Reading PDF files from asstes folder

I have list of PDF files need to Place in asstes folder,my requirement is to read files from asstes and display it inside a listview.
if we click on each list item need to read respective PDF file
I have followed this blog http://androidcodeexamples.blogspot.in/2013/03/how-to-read-pdf-files-in-android.html
But here they have given reading a PDF files from External Storage Directory
I want to implement the same reading files from Asstes Folder
Could any one help How to implement the same example reading files from asstes?
You cannot open the pdf file directly from the assets folder.You first have to write the file to sd card from assets folder and then read it from sd card.
Try out the below code to copy and read the file from assets folder:
//method to write the PDFs file to sd card
private void PDFFileCopyandReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "test.pdf");
try
{
in = assetManager.open("test.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
readFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/test.pdf"),
"application/pdf");
startActivity(intent);
}
private void readFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
Open the file from sdcard as below:
File file = new File("/sdcard/test.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Also provide a permission to write into your external storage in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

File copying: what am I doing wrong?

Sorry,
I have no experience with the Android file system, I am struggling to understand it via the documentation and the tutorials.
I am trying to copy a file from a location to the external storage of my app.
final File filetobecopied =item.getFile();
File path=getPrivateExternalStorageDir(mContext);
final File destination = new File(path,item.getName());
try
{copy(filetobecopied,destination);
}
catch (IOException e) {Log.e("",e.toString());}
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Toast.makeText(mContext,"COPIED",Toast.LENGTH_SHORT).show();
}
public File getPrivateExternalStorageDir(Context context) {
File file = context.getExternalFilesDir(null);
if (!file.mkdirs()) {
Log.e("", "Directory not created");
}
return file;
}
I get the following error:
09-18 10:14:04.260: E/(7089): java.io.FileNotFoundException: /storage/emulated/0/Android/data/org.openintents.filemanager/files/2013-08-24 13.18.14.jpg: open failed: EISDIR (Is a directory)
http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String) use this example of code and use standart examples of google)
Try
final File destination = new File(path + "/" + item.getName());
instead.
I assume, folder directory is not created or your external storage state is not mounted.
Before you perform file operations, you should sanitize your path. Following code is a sample code that I often use.
public File sanitizePath(Context context) {
String state = android.os.Environment.getExternalStorageState();
File folder = null;
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
folder = new File(context.getFilesDir() + path);
// path is the desired location that must be specified in your code.
}else{
folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + path);
}
if (!folder.exists()){
folder.mkdirs();
}
return folder;
}
And be sure about that, when your directory has to be created before you perform file operations.
Hope this will help.
EDIT: By the way, you have to add following permission to your manifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to read PDF file saved to internal storage of device?

I am using following code to download and read a PDF file from internal storage on device.
I am able to download the files successfully to the directory:
data/data/packagename/app_books/file.pdf
But I am unable to read the file using a PDF reader application like Adobe Reader.
Code to download file
//Creating an internal dir;
File mydir = getApplicationContext().getDir("books", Context.MODE_WORLD_READABLE);
try {
File file = new File(mydir, outputFileName);
URL downloadUrl = new URL(url);
URLConnection ucon = downloadUrl.openConnection();
ucon.connect();
InputStream is = ucon.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte data[] = new byte[1024];
int current = 0;
while ((current = is.read(data)) != -1) {
fos.write(data, 0, current);
}
is.close();
fos.flush();
fos.close();
isFileDownloaded=true;
} catch (IOException e) {
e.printStackTrace();
isFileDownloaded = false;
System.out.println(outputFileName + " not downloaded");
}
if (isFileDownloaded)
System.out.println(outputFileName + " downloaded");
return isFileDownloaded;
Code to read the file
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
try {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
File fileToRead = new File(
"/data/data/com.example.filedownloader/app_books/Book.pdf");
Uri uri = Uri.fromFile(fileToRead.getAbsoluteFile());
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (Exception ex) {
Log.i(getClass().toString(), ex.toString());
Toast.makeText(MainActivity.this,
"Cannot open your selected file, try again later",
Toast.LENGTH_SHORT).show();
}
All works fine but the reader app says "File Path is not valid".
Your path is only valid for your app. Place the file in a place where other apps can 'see' it. Use GetExternalFilesDir() or getExternalStorageDirectory().
Note about files which are created inside the directory created by Context.getDir(String name, int mode) that they will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
So you can use Context.openFileOutput(String name, int mode). I'm re-using your code for an example:
try {
// Now we use Context.MODE_WORLD_READABLE for this file
FileOutputStream fos = openFileOutput(outputFileName,
Context.MODE_WORLD_READABLE);
// Download data and store it to `fos`
// ...
You might want to take a look at this guide: Using the Internal Storage.
If you would like to keep the file app specific, you can use PdfRenderer available for Lollipop and above builds. There are great tutorials on google and youtube that work well. The method you are using is a secure way to store a PDF file that is only readable from inside the app ONLY. No outside application like Adobe PDF Reader will be able to even see the file.It took me a lot of seaching but I found a solution to my specific usage by using this site and especially youtube.
How to download PDF file from asset folder to storage by making folder
make sure you have storage permission are given like marshmallow device support etc then follow these steps
private void CopyReadAssets()
{
AssetManager assetManager = getContext().getAssets();
FileInputStream in = null;
FileOutputStream out = null;
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File(Environment.getExternalStorageDirectory()+File.separator+ "A_level");
File dir2;
if (dir.exists() && dir.isDirectory()){
Log.e("tag out", ""+ dir);
}else {
dir.mkdir();
Log.e("tag out", "not exist");
}
File file = new File(dir, mTitle+".pdf");
try
{
Log.e("tag out", ""+ file);
out = new FileOutputStream(file);
in = new FileInputStream (new File(mPath));
Log.e("tag In", ""+ in);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag out", ""+ out);
Log.e("tag In", ""+ in);
Log.e("tag", e.getMessage());
Log.e("tag", ""+file);
Log.i("tag",""+sdcard.getAbsolutePath() + "A_level");
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}

Categories

Resources