Writing file in Android always fails - android

I want to write text to file in Android. I tried writing to sdcard and public part of internal storage. I always got FileNotFound exception. I tried to get path by Environment.getExternalStorageDirectory().getAbsolutePath() and by Environment.getExternalStoragePublicDirectory(Enviroment.DIRECTORY_DCIM).getAbsolutePath()(it does not metter the file is not a picture, I suppose) and both returned: "storage/emulated/0" and "storage/emulated/0/DCMI" respectively. I have also tried direct path "/sdcard/MyFile/output.txt" and "mnt/sdcard/MyFile/output.txt". I have checked on most stackoverflow.com answears in such topic but I got only code similar to mine. (like from here)
Example of my code (I tried more variations):
try {
File dir = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyFile");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "output.txt");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(file);
stream.write(("some text").getBytes());
stream.close();
toast = Toast.makeText(context, "Saving file successful.", Toast.LENGTH_SHORT);
toast.show();
} catch (Exception e) {
toast = Toast.makeText(context, Environment.getExternalStorageDirectory().getAbsolutePath(), Toast.LENGTH_SHORT);
//toast = Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT);
toast.show();
}

You have to set the
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
permission in your AndroidManifest.xml file.
If you run your app on Android 6.0 or higher you have to request this permission at runtime.
Request App Permissions

I am sorry to all you guys to waste your time. The problem was in permission setting. Here is the answear.

Related

How to create directories in /storage/extSdCard path in android java?

I can see sdcard folder contents by using this
File f = new File("/storage/extSdCard");
if (f.exists()) {
File[] files = f.listFiles();
if (files != null) {
for (File filz : files) {
Toast.makeText(this, filz.getName() + "", Toast.LENGTH_SHORT).show();
}
}
}
But when i try to create directories
File dir = new File("/storage/extSdCard/Android/Mayor");
try {
if (!dir.exists()) {
if (dir.mkdirs()) {
Toast.makeText(this, "Folder Created", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Folder Not Created", Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "WTF", Toast.LENGTH_LONG).show();
}
Its doesnt create at all. Any idea?
// create a File object for the parent directory
File myDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
myDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(myDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
Note:
It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change if a phone comes along which has something other than an SD Card (such as built-in flash, a'la the iPhone). Either way you should keep in mind that you need to check to make sure it's actually there as the SD Card may be removed.
UPDATE:
Since API Level 4 (1.6) you'll also have to request the permission. Something like this (in the manifest) should work:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You need to use DocumentFile.createDirectory(displayName) to create a directory on a removable SD card. See https://stackoverflow.com/a/35175460/1048340
File mnt = new File("/storage");
if (!mnt.exists())
mnt = new File("/mnt");
File[] roots = mnt.listFiles();
For read external sdcard, you need to mount sdcard path first then after you can able to use external sdcard path.

How to Create a folder in external sdcard in Android 4.4.2(Kitkat) API level 19

I try a lot to create a folder in SD card in android 4.4.2 version.
i try the following code
String dirName="Test";
File file = new File(Environment.getExternalStorageDirectory(), dirName);
boolean status = file.mkdir();
if (status)
Toast.makeText(MainActivity.this,
"Directory created successfully", Toast.LENGTH_SHORT)
.show();
else
Toast.makeText(MainActivity.this, "Directory create failed",
Toast.LENGTH_SHORT).show();
but it creates a folder in internal storage.
and I try another code is
String path=System.getenv("SECONDARY_STORAGE");
File file=new File(path +"/Test123");
file.mkdir();
it creates a folder in External SDCARD in android 4.1 but not in android 4.4.2
So how can i create a folder in External sdcard in android 4.4.2??
If anyone know please help me..
Thanks in advance
The documentation states that
Applications should not directly use this top-level directory, in
order to avoid polluting the user's root namespace. Any files that are
private to the application should be placed in a directory returned by
Context.getExternalFilesDir, which the system will take care of
deleting if the application is uninstalled.
where with top-level directory they mean the return value of Enviroment.getExternalStorageDirectory()
Using getExternalFilesDir you will have
File file = new File (getExternalFilesDir(null), dirName);
if (!file.exists()) {
boolean status = file.mkdir();
if (status) {
Toast.makeText(MainActivity.this, "Directory created successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Directory create failed", Toast.LENGTH_SHORT).show();
}
}
also you should be aware of the fact that mkdir() returns false if the directory already exists
This should be self-explanatory.
String folderName = "NewFolder";
File file = new File(Environment.getExternalStorageDirectory(),
folderName);
if (!file.exists()) {
file.mkdirs();
}
Make sure you have added WRITE_EXTERNAL_STORAGE permission in your manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Credits to Dhaval

Created folder is not visible in the file explorer..

I have a problem with creating a folder and a file on the sdcard.
Here's the code:
File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/folder");
boolean success;
if (!folder.exists()) {
success = folder.mkdirs();
}
File obdt = new File(folder, "file.txt");
try {
success = obdt.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
With this code I expect to create the folderfolder in the Download folder of the sdcard and in this the file file. I want that the user can access the file. So I want to put it in a shared folder.
The success variable is true and when I run the code again the folder already exists and doesnt come in the if-block.
But I can't see the created folder and file on the sdcard in file explorer.
Info:getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() returns storage/sdcard/Download
I work with a Galaxy Nexus.
Damn! :)
Now I solved my problem...I was misunderstanding the operation of creating files in the file system.
When I spoke of file explorer I meant the file explorer of the operating system and NOT the file explorer in the DDMS :).
I thought when I create a file I will see it in the file explorer of the operating system but when the device is connected to the PC the files can only be seen in the DDMS file explorer.
Sorry I'm new to Android ;)
When the App is running standalone without PC connection and afterwards I connect with the PC I see the created files and folders of course :)
Thanks for help
Any errors from logcat?
Else: try something like Log.I("PATHNAME",folder.absolutePath()); and then look in your logcat to make sure where you are creating the folder where you think it is.
If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If you have already done that see if :
File obdt = new File(/sdcard/folder/file.txt)
try {
success = obdt.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
works.
You cannot see the folder/file in explorer? Maybe it is because the MediaScanner is active, but not adding your files. You can do this in your program or switch the Media Scanner of somewhere in your phone settings.
MediaScanner
Trigger MediaScanner
Try this out.
File dir = new File(Environment.getExternalStorageDirectory()
+ "/XXX/Wallpapers/");
File[] files = dir.listFiles();
if (files == null)
{
int numberOfImages = 0;
BitmapDrawable drawable = (BitmapDrawable) imageView
.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment
.getExternalStorageDirectory();
new File(sdCardDirectory + "/XXX/Wallpapers/").mkdirs();
File image = new File(sdCardDirectory
+ "/XXX/Wallpapers/Sample" + numberOfImages + ".JPG");
boolean success = false;
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(
getApplicationContext(),
"Image saved successfully in Sdcard/XXX/Wallpapers",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG)
.show();
}
Dont forget to add permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Apparently there is a known bug in MTP.
Issue 195362
All phones using MTP instead of USB Mass storage do not properly show the list of files when that phone is connected to a computer using a USB cable. Android apps running on the device also cannot see these files.
It is actually as old as 2012
I've encountered the same problem: created files and folders don't show immediately after being written to sdcard, despite the file being flushed and closed !!
They don't show on your computer over USB or a file explorer on the phone.
I observed three things:
if the absolute path of the file starts with /storage/emulated/0/ it doesn't mean it'll be on your sdcard - it could be on your main storage instead.
if you wait around 5 minutes, the files do begin to show over USB (i.e. Windows explorer and built-in file explorer)
if you use adb shell ls /sdcard from terminal, then the file does show! you could use adb pull ... to get the file immediately. You could probably use DDMS too.
Code I used was:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(myArrayList);
try {
File externalDir = getExternalStorageDirectory();
File newFile = new File(externalDir, "myfile.txt");
FileOutputStream os = new FileOutputStream(newFile);
os.write(json.getBytes());
os.flush();
os.close();
Timber.i("saved file to %s",newFile.getAbsoluteFile().toString());
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Save to private external storage failed. Error message is " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
and
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(myArrayList);
try {
File externalDir = getExternalStorageDirectory();
File newFile = new File(externalDir, "myfile.txt");
FileWriter fw = new FileWriter(newFile);
fw.write(json);
fw.flush();
fw.close();
Timber.i("saved file to %s",newFile.getAbsoluteFile().toString());
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Save to private external storage failed. Error message is " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
why is it like this? Seems like another one of those "Android-isms" that you have to suffer through the first time you experience it.

checking if a directory is created or not, fails?

I'm trying to create a directory, and i'm checking whether it is created successfully or not but displaying a text on the screen, but nothing to be displayed.
Java code:
public void createDirectory() {
try {
String strDirectory = "test";
boolean success = ( new File(strDirectory)).mkdir();
if (success) {
Toast.makeText(getBaseContext(), "Directory "+strDirectory+" created", Toast.LENGTH_SHORT);
} else {
Toast.makeText(getApplicationContext(), "error occured", Toast.LENGTH_SHORT);
}
} catch (Exception e) {
Log.e("Error", "Error creating directory");
}
}
put .show() end of Both Toast....
Toast.makeText(getBaseContext(), "Directory "+strDirectory+" created",
Toast.LENGTH_SHORT).show();
Did you add uses-permission write external storage to your manifest?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I actually don't know where it's trying to create the directory since you are not qualifying the entire path. what are you trying to do?
If you are trying to create it on the SD card, do this,
File f = new File(Environment.getExternalStorageDirectory(), "myfile.txt");
http://developer.android.com/reference/android/os/Environment.html
Note that this file will be readable by all apps.
If you are trying to create a file that's private to the app, do this,
OutputStream os = context.openFileOutput("myfile.txt");
http://developer.android.com/reference/android/content/Context.html
Note that this method is reserved for small files as it uses the internal storage which is limited on many devices.
Finally, always print the stack trace,
Log.e("mytag", "some message", e);
9 times out of ten, this will point you directly to the problem.

Can I access the files I create with USB

I'm lost here.
I create files using this (stripped) code :
File dir = getBaseContext().getDir(dirPath, MODE_WORLD_WRITEABLE);
try {
File file = new File(dir, fileName);
FileOutputStream fous = new FileOutputStream(file);
fous.write(data);
fous.flush();
fous.close();
long l = file.length();
Log.i("PpCameraActivity", "File size : " + l);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error while trying to write photo file", Toast.LENGTH_LONG).show();
}
I can verify with logcat that my file seems to be created (it has a not null lenght). But I cannot see it when I connect my android device to my PC.
So... where is my file ? Is it hidden ? Erased ?
EDIT : I'm now trying to write on the SDCard specifically, using this :
File root = Environment.getExternalStorageDirectory();
File jpegFile = new File(root.getAbsolutePath() + "/myApplication/" + filePath);
try {
jpegFile.mkdirs();
FileOutputStream fous = new FileOutputStream(jpegFile);
fous.write(data);
fous.flush();
fous.close();
Log.i("PpCameraActivity", "File written : " + jpegFile.getAbsolutePath());
Toast.makeText(getBaseContext(), "File written : " + jpegFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
long l = jpegFile.length();
Log.i("PpCameraActivity", "File size : " + l);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Error while trying to write photo file", Toast.LENGTH_LONG).show();
}
But I get a FileNotFoundException on the FileOutputStream creation...
OK found it.
Not an Android problem but just my error (not the first time) : mkdirs must be applied to the parent file, not the file I want to write...
So, for people interested :
Access the sd card using
File root = Environment.getExternalStorageDirectory();
Don't forget to require this permission
WRITE_EXTERNAL_STORAGE
Then make, as usual, mkdirs and file creation.
And don't forget : the android device cannot write on the sdard while it is mounted on you PC.
You probably aren't writing to the SD card, and the SD contents are all you can see from a USB connection.
Try something like this: http://androidgps.blogspot.com/2008/09/writing-to-sd-card-in-android.html (just the first thing that came up when I searched for "Android write to SD card").

Categories

Resources