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" />
Related
Trying to copy a PDF file (template) to a custom directory in the external storage (non-sd card).
public void copyPDFToExternal(String newFileName) throws IOException {
// Create directory folder if it doesnt exist.
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "pdfFolder");
if (!folder.exists()){
folder.mkdir();
}
// Copy template
InputStream in = getResources().openRawResource(R.raw.pdf_template);
FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() +
File.separator + "pdfFolder/"+newFileName+".pdf");
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0 ) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
}
I have added the following to AndroidManifest.xml, not in the application tag.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Full error: http://pastebin.com/TBtbekiB
If you need me to post anything else let me know.
Where have I gone wrong?
Update: No longer crashes but now doesn't seem to do anything... the mkdirs returns true.
public void copyPDFToExternal(String newFileName) throws IOException {
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/test/");
if (!folder.exists()){
if (!folder.mkdirs()){
eme.setText("Failed");
return;
};
}
InputStream in = getResources().openRawResource(R.raw.ohat);
FileOutputStream out = new FileOutputStream(folder.getAbsolutePath() +"/"+newFileName+".pdf");
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0 ) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
}
I've also added a permission request, this is a little long so using pastebin.
http://pastebin.com/KgivWNuc
Edit 2:
So it seems it does work, just the directory cannot be see when the device is connected to a computer (in MTP mode). But I guess that's another issue.
if you are installing in device os version android M and more you need to take permission at runtime. Adding in manifest alone is not sufficient. Refer this for more details.
Can you specify which external storage you are using as you have said it is (non SD Card) because if you are using Environment.getExternalStorageDirectory() then it will give you the path of SD Card Storage, something like this /storage/emulated/0/ where 0 represents primary storage device.
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.
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);
}
I am using the following code to unzip a set of files (containing folders as well):
private boolean unpackZip(String path, String zipname)
{
InputStream is;
ZipInputStream zis;
try
{
String filename;
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null)
{
// zapis do souboru
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(path + filename);
// cteni zipu a zapis
while ((count = zis.read(buffer)) != -1)
{
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
The code fails on FileOutputStream fout = new FileOutputStream(path + filename) with the error:
java.io.FileNotFoundException: /storage/emulated/0/BASEFOLDER/FOLDER1/FILE.png
BASEFOLDER already exists, that is where I am trying to unzip the folder to. If I manually (or programmatically) create FOLDER1, the code runs fine and successfully unzips. I believe it is crashing because the very first file (ze) is named FOLDER1/FILE.png and FOLDER1 hasn't been created yet. How do I get around this? I know other people have used this code, I find it unlikely that it randomly doesn't work for me...
Have you got this in your AndroidManifest.xml file?
Add Write to external Storage permission
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
I had the same problem. After several investigation I found that. put following single line in your code:
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
zis.closeEntry(); // <<<<<< ADD THIS LINE
continue;
}
Sometime the extract files has been extracted before its parent directory is created, for example:
File A inside directory B. But B directory is not created, index of files listing below cause the issue:
dir_b/file_a.txt
dir_b/
dir_b/file_c.txt
So, to sure directory created before file extracting, you need to create parent directories first, for example:
val targetFile = File(tempOutputDir, zipEntry.name)
if (zipEntry.isDirectory) {
targetFile.mkdirs()
} else {
try {
try {
targetFile.parentFile?.mkdirs() // <-- ADD THIS LINE
} catch (exception: Exception) {
Log.e("ExampleApp", exception.localizedMessage, exception)
}
val bufferOutputStream = BufferedOutputStream(
FileOutputStream(targetFile)
)
val buffer = ByteArray(1024)
var read = zipInputStream.read(buffer)
while (read != -1) {
bufferOutputStream.write(buffer, 0, read)
read = zipInputStream.read(buffer)
}
bufferOutputStream.close()
} catch (exception: Exception) {
Log.e("ExampleApp", exception.localizedMessage, exception)
}
}
please somebody tell me what is the folder of sdcard and how can i create files in it.because i am new to android and i have googled so much but could not find any comprehensive stuff.i want to create file in sdcard manually. please help.
here is my code i have written but now it says fileNotFoundException. hence i have created a file in sdcard but still it is not recognisizing the file.any suggestions please.
try
{
String root = android.os.Environment.getExternalStorageDirectory().getPath();
File gpxfile = new File(root, "sijjeel.txt");
//FileWriter writer = new FileWriter(gpxfile);
FileOutputStream writer = new FileOutputStream(gpxfile);
writer.write(bArray, 0, bArray.length);
writer.flush();
writer.close();
}
thanks alot
Path to sdcard is:
android.os.Environment.getExternalStorageDirectory().getPath()
To write a file, you can use the regular java.io.File methods for that.
For example, for creating a text files I use a helper method like this:
/**
* Stores text content into a file
* #param filename Path to the output file
* #param content Content to be stored in file
* #throws IOException
*/
public void storeFile(final String filename, final String content, String charSet)
throws IOException {
if (charSet==null) charSet = "utf-8";
Writer w = new OutputStreamWriter( new FileOutputStream(filename), charSet );
w.write(content);
w.flush();
w.close();
}
public void storeFile(final String filename, final String content)
throws IOException {
storeFile(filename, content, null);
}
or copying a file to sdcard:
public static final void copyfile(String srFile, String dtFile){
try{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied to " + f2.getAbsolutePath());
} catch(FileNotFoundException ex){
System.out.println(ex.getMessage() + " in the specified directory.");
System.exit(0);
} catch(IOException e){
System.out.println(e.getMessage());
}
}
It's /sdcard (if you actually have a card in it)
The code you provided will create the file if it is not already there. Make sure you run your program on the emulator that has an SD card mounted. If it doesn't you can see an icon in the notification area saying so.