Can't write file on SD-card (Is a directory) - android

I'm getting the following error when trying to write midi-file on the Android SD-Card:
12-14 16:22:22.219: ERROR/Thread writer(1108): java.io.FileNotFoundException: /mnt/sdcard/folder/midifiles/file.mid (Is a directory) in /mnt/sdcard/folder/midifiles/
That's the relevant code:
public void writeFile(String filename, String dir, int bpm) throws Exception {
File f = new File(dir,filename);
if(!f.exists()) {
f.mkdirs();
if(!f.createNewFile()) {
return;
}
}
FileOutputStream fos = new FileOutputStream(f);
I'm receiving the path via
Environment.getExternalStorageDirectory()
The relevant permission has been included as well.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The file-writer is located in an external project/library... if this is in any case useful to know.
I guess that this is kind of a simple mistake, but I honestly have no idea what went wrong here.
Thanks in advance.

You are creating the directory /mnt/sdcard/folder/midifiles/file.mid with
f.mkdirs();
You should just do:
File f = new File(dir);
if(!f.exists()) {
f.mkdirs();
File f1 = new File(dir,filename);
if(!f1.createNewFile()) {
return;
}
}
or just
File f = new File(dir,filename);
if(!f.exist()) {
f.createNewFile();
return;
}

Are you running this on your phone? or connected to your pc? because it may be looking on your pc.

Related

Unable to create external file - EACCES (permission denied)

When trying to create a simple .txt or .xml external file (NOT on SD card), my app is throwing a FileNotFoundException. If I let the system pick the path (returns /storage/emulated/legacy) it throws EACCES (permission denied). Same as when I set the path manually to "/android/data" (returns /storage/emulated/0/android/data) or "/download" (returns /storage/emulated/0/Download) - both throw EACCES. If I set path to "/document" it throws ENOENT (no such file or directory).
As see below in my code, I do a check before to make sure that external storage is available and not read-only.
I ran this on 2 devices, running 4.4.2 and 4.4.4
I also added
"android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
in the manifest as suggested in SO answers to try and force the device to use it's own file system and not the PC's when running app through USB, but it seems to keep giving me a path derived from /emulated/
I try debugging from the device itself using the developer options and thus eliminating the possibility of the app accessing the PC's storage, but the debugger on the device just hangs trying to attach.
Of course I have as well:
"android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18"
This is very frustrating as there are some similar questions on SO but with very accepted answers.
public static File getExternalStorageDirectory() {
Log.i("EXTERNAL STORAGE DIR", EXTERNAL_STORAGE_DIRECTORY.toString());
return EXTERNAL_STORAGE_DIRECTORY;
}
public static final File EXTERNAL_STORAGE_DIRECTORY = getDirectory("EXTERNAL_STORAGE", "android/data");
public static File getDirectory(String variableName, String defaultPath) {
String path = System.getenv(variableName);
return path == null ? new File(defaultPath) : new File(path);
}
public boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
public boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
public void writeToSettingsFile(String name, String value){
// File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "/settings.txt");
// File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), fileUrl);
// File myDir = getDirectory("EXTERNAL_STORAGE", "android/data");
// File myDir = getExternalStorageDirectory();
// File myDir = new File("download");
File myDir = new File(Environment.getExternalStorageDirectory() + "/android/data");
if(!myDir.exists()){
myDir.mkdirs();
}
try{
String fname = "settings.txt";
File file = new File (myDir, fname);
FileOutputStream fOut = new FileOutputStream(file);
Toast.makeText(context, "you made it, fOut!!!!", Toast.LENGTH_LONG).show();
props.setProperty(name, value);
props.store(fOut, "Settings Properties");
// props.storeToXML(fOut, "Settings Properties");
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("WTF", "No file found!");
}
catch (IOException e) {e.printStackTrace();
}
}
I think the problem is in your this line
android:maxSdkVersion="18" .
Cause You are testing on 4.4.2. And this device has api level 19.
Okay this is the solution :
public void writeToSettingsFile(String name, String value){
// File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "/settings.txt");
// File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), fileUrl);
// File myDir = getDirectory("EXTERNAL_STORAGE", "android/data");
// File myDir = getExternalStorageDirectory();
// File myDir = new File("download");
File myDir = new File(this.getExternalFilesDir(null), name);
if(!myDir.exists()){
myDir.mkdirs();
}
try{
String fname = "settings.txt";
File file = new File (myDir, fname);
FileOutputStream fOut = new FileOutputStream(file);
fOut.write(value.getBytes());
// props.storeToXML(fOut, "Settings Properties");
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.e("WTF", "No file found!");
}
catch (IOException e) {e.printStackTrace();
}
}
Try this method. The problem was you cant get internal directory like this
File myDir = new File(Environment.getExternalStorageDirectory() + "/android/data"); // You don't have the permission to do this
if you want to write on internal storage you can get directory like this
File myDir = new File(this.getExternalFilesDir(null), name);
And you can take a look to For more information about saving files

java.io.FileNotFoundException: /storage/emulated/0/saved_images/grub.jpg: open failed: ENOENT (No such file or directory)

Am using the below code to save an image in sd card but I keep on getting this below exception
private void SaveImage(Bitmap finalBitmap,String filename) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = filename;
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Am I missing out anything here?
If you face this problem in Android version 10 then Open the manifest file and add this line to your application tag.
<application android:requestLegacyExternalStorage="true" .....>
This issue is because of the introduction of scoped storage introduced in Android 10. And make sure that you add permission requests in manifest and take runtime permission from the user. You need runtime permission from the user in latest android versions.
Modify your code, as you are not creating the directory:
private void SaveImage(Bitmap finalBitmap,String filename) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = filename;
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
file.createNewFile();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Starting with SDK version 30, you can NOT extend android:requestLegacyExternalStorage="true". Instead modify your ImageLoader library a little. I see you have to modify your file path: File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "saved_images"); into something like File dir = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "saved_images");. This should do a trick.
This is how I read a file from storage when I was checking for a timestamp in a text file. Line 2 is probably the best bet for you.
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/path");
dir.mkdirs();
File file = new File(dir, ".storage.txt");
Reader pr;
String line = "";
try {
pr = new FileReader(file);
int data = pr.read();
while (data != -1) {
line += (char) data;
data = pr.read();
}
pr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//do stuff with line
From Android 6.0.0 you need to use this code :
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
make sure you placed the permissions on Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<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" />

Android does not make director(mkdir)

SOLVED
i change it a litle bit
File path = new File(Environment.getExternalStorageDirectory(), "AndroidPaint");
File file = new File(path, tmpImg);
path.mkdirs();
if(!file.exists()) {
file.createNewFile();
}
os = new FileOutputStream(file);
source.compress(CompressFormat.JPEG, 100, os);
os.flush();
os.close();
also problem could be source Bitmap i discovered then was null
PROBLEM
on my Android program i want save bitmap on external store i got permission for do that
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
and got some code for that
public class SaveOpen {
public static void save(Bitmap source) {
String tmpImg = String.valueOf(System.currentTimeMillis()) + ".jpg";
OutputStream os = null;
try {
File dir = new File(Environment.getExternalStorageDirectory(), "myapp");
if (!dir.mkdirs()) {
Log.e("save", "Directory not created");
}
File file = new File(dir, tmpImg);
if(!file.exists()) {
file.createNewFile();
}
os = new FileOutputStream(file);
source.compress(CompressFormat.JPEG, 100, os);
os.flush();
os.close();
}
catch (IOException e) {
Log.d("save", e.getMessage());
}
}
}
but when i press save button on my app i get
open failed: ENOTDIR (Not a directory)
exception, what i do wrong.? i tried all guide i found in google, pls help
try this:
String myDir = Environment.getExternalStorageDirectory() + "/myapp";
File dir = new File(myDir);
On older devices access to external storge is not possible if there's is USB connection (disk mode), so log what is Environment.getExternalStorageDirectory() returning in your case.
I met the same problem, it seems like a bug on Android, I mkdir in the command line by adb, also failed. Then I try to restart the phone, never happen again.
My problem solved by add permissions to access external storage:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Android - downloading file, java.io.FileNotFoundException

I may be way off here, but I am trying to download a file and store it in the downloads folder on my phone. I am getting a "java.io.FileNotFoundException" error, because the file doesn't exist, because I'm trying to download it...what am I doing wrong?
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File dir = new File(PATH);
dir.mkdirs();
File outputFile = new File(dir, "downloadFile");
FileOutputStream fos = new FileOutputStream(outputFile);
This fails, with the following:
java.io.FileNotFoundException: /mnt/sdcard/download/downloadFile (Permission denied)
I am using the WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permissions....
Please try following updated code,
String PATH = Environment.getExternalStorageDirectory() + "/download";
File dir = new File(PATH);
dir.mkdirs();
File outputFile = new File(dir, "downloadFile");
if ( !outputFile.exists() )
{
outputFile.create();
}
FileOutputStream fos = new FileOutputStream(outputFile);
There is a "/" after the download. This way Android is thinking that you are creating Recursive Directory. While using mkdirs(), you can not create recursive directories.
You can also check my answer for same in Java ME here.
Add Permission to write external memory in your Manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Here you want to make directoy?
it there is already folder of download than use this code directly.
// create a File object for the parent directory
File Directory = new File("/sdcard/download/");
Directory.mkdirs();
// create a File object for the output file
File outputFile = new File(Directory, downloadFile);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change

Categories

Resources