I am new to android development and I have tried to read a directory from my sd card but didn't got succeeded. Below is the code which I wrote to achieve it
File sdcard = Environment.getExternalStorageDirectory();
if(sdcard.exists()) {
Log.d("Sd card", "Sd card exist");
File[] file_names = sdcard.listFiles();
for(File x : file_names) {
Log.d("File Name",x.getName());
}
}
Control passed the if condition and then I got an NullPointerException at "for each" loop line. Probably function sdcard.listFiles() is returning null. I have an Sd card with many folders and files. Actually I have to create a directory file object for directory "Attachments" which is available on my sd card. I also tried the following code to achieve the same.
File file = new File(android.os.Environment.getExternalStorageDirectory() + File.separator + "Attachments");
and
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "Attachments");
on both code when I called the function file.exists(), it returned false.
I have also checked whether sd card is mounted or not by the following code.
String sdCardAvail = Environment.getExternalStorageState();
if(sdCardAvail.equals(Environment.MEDIA_MOUNTED))
Log.d("Card status", "Sd card Available");
The above code has printed "Sd card Available" at log cat.
So please help me out to know whether I am doing it correct or missing any thing.
Thanks....
In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGEorWRITE_EXTERNAL_STORAGE system permissions. For example:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
If you need to both read and write files, then you need to request only the WRITE_EXTERNAL_STORAGE permission, because it implicitly requires read access as well.
Also See This Documentation. It Will solve all your future regarding Storage problems.
Related
I have write a code to find if SD card path if available which is like this
File[] paths = ContextCompat.getExternalFilesDirs(context, null);
if (paths.length > 1) {
if (paths[1] != null) {
root = paths[1].getAbsolutePath();
// for sd card
} else {
root = Environment.getExternalStorageDirectory().toString();
}
} else {
root = paths[0].getAbsolutePath();
}
I am saving my data in path "/storage/4130-1912/Android/data/com.enable/files" but I wanted to save data outside Android folder.
I have also tried to make an directory outside the Android folder.But unable to make it.I am testing in Lave phone with version Marhmallow
As you are using Marshmallow, you should be requesting runtime permissions (more details here). Despite that, you may add the WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for external storage access. You can find more information on how to here.
You can access the external storage path like this: Environment.getExternalStorageDirectory().getAbsoluteFile(). If you are getting FileNotFoundException, it's probably because you didn't add an additional "/" before your file. Example:
File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +
"/your_file.txt");
I am saving my data in path "/storage/4130-1912/Android/data/com.enable/files"
Ok. Go ahead. You will succeed.
but I wanted to save data outside Android folder.
Well that is not possible anymore on modern Android systems.
Even inside the Android folder you can only write to mentioned private directory for your app.
If you want to write to the whole micro SD card then use the storage access framework.
This will help you
As miguelarc said:
As you are using Marshmallow, you should be requesting runtime
permissions (more details here). Despite that, you may add the
WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for external
storage access.
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getPackageName() + "/yourdir");
if (f.mkdirs() || f.isDirectory())
Log.e("path",f.getPath());
//do what you want
}
I am trying to create a folder and then after that do some file IO operations!
I am using a sony Xperia Z to test this out!
I know right now I've hardcoded the location but it doesn't let me create folders!
File appPath = new File("/storage/sdcard1/folder");
if (!appPath.exists()) {
appPath.mkdirs();
}
I am using a targetSdkVersion of 22
And having lollipop on my phone.
I tried
appPath.mkDir();
as well but all this gives a value of False.
And i have added permissions to manifest
<uses-permission name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission name="android.permission.READ_EXTERNAL_STORAGE" />
And I tried many different open source file manager but none are able to create folders, But ES file Manager is able to create folders and do File IO operations!
Don't hardcode global paths like /sdcard, use Environment.getExternalStorageDirectory() and related methods instead. Here is a working sample.
public static String getNewFolderPath() {
File folder = new File(Environment.getExternalStorageDirectory()
.toString() + File.separator + "folder");
if (!folder.exists())
folder.mkdirs();
return folder.getAbsolutePath();
}
EDIT:
For more info check:
Find an external SD card location
#CommonsWare Answer
#Aleadam Answer
Hope it helps!
I use the following to check if a directory exists and if it doesn't it then creates it
final String appPath = String.format("%s/DataFiles", Environment.getExternalStorageDirectory());
File f = new File(appPath);
if(f.exists() && f.isDirectory()){
Toast.makeText(getBaseContext(), "Exists", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getBaseContext(), "DOES NOT Exist", Toast.LENGTH_LONG).show();
f.mkdir();
This works fine on my S3 that has a sd card inserted
When I try it on anither phone that doesnt have an sd card in it recognises that the directory doesnt exists and then doesnt create the directory
Any ideas whats wrong
Mark
BTW I have tried inserting an sd card but doesn't make a difference it still doesn't create directory.
Before any operation you need to check if external storage is available.
http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
if sd-card is not available or is not available for writing you need to use device storage:
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
I have a routed device and when I do this
adb shell cat /data/misc/bluetooth/dynamic_auto_pairing.conf
it prints the content of this file.
But in my code when I write something like this, it says that the file does not exist. Well from the console I see it I know is there, but from code I can't read it. My question is what is the problem , am I missing some permission or what is the problem ? can someone provide me with some code to read the content from this file.
Thanks
File pa = new File("/data/misc/bluetooth/","dynamic_auto_pairing.conf");
//this doesn't works also
//File pa = new File("/data/misc/bluetooth","dynamic_auto_pairing.conf");
//File pa = new File("/data/misc/bluetooth/dynamic_auto_pairing.conf");
if(pa.exists()){
Log.v("tag", "does exists");
}else{
Log.v("tag", "does NOT exist");
}
If the file is on sdcard, try:
File pa = new File(Environment.getExternalStorageDirectory() + "/data/misc/bluetooth/dynamic_auto_pairing.conf");
Also try to add:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
outside <application></application> in your manifest file.
EDIT
If the file is in internal memory: Your app can read only from a special folder in internal memory. The path to that folder is returned by:
getFilesDir().getAbsolutePath()
So put the file there and read it with openFileInput().
More info:
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
From the docs for File...
public File (String dirPath, String name)
Constructs a new File using the specified directory path and file name, placing a path separator between the two.
In your code you are using...
File pa = new File("/data/misc/bluetooth/","dynamic_auto_pairing.conf");
...and because your dirPath ends with a separator "/data/misc/bluetooth/" it will result in two separators. In other words, effective path will be...
/data/misc/bluetooth//dynamic_auto_pairing.conf
Note the // after 'bluetooth`
If you are using android 6.0 or higher. You must request permission in code.
Im trying to save data to sdCard first i tried to saave it privately within app directory on externalStorage using getExternalFilesDir but gives me nullPointerException so i tried the other way given below it worked but when i want to store files into a custom directory that i want to named myself it give me error:
FileOutputStream os;
dirName = "/mydirectory/";
try {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)){
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + dirName);
dir.mkdirs();
//File file = new File(this.getExternalFilesDir(null), this.dirName+fileName); //this function give null pointer exception so im using other one
File file = new File(dir, dirName+fileName);
os = new FileOutputStream(file);
}else{
os = context.openFileOutput(fileName, MODE_PRIVATE);
}
resizedBitmap.compress(CompressFormat.PNG, 100, os);
os.flush();
os.close();
}catch(Exception e){
}
ErrorLog:
java.io.FileNotFoundException: /mnt/sdcard/mvc/mvc/myfile2.png (No such file or directory)
Your directory "/mnt/sdcard/mvc/mvc" may not exist. What about changing your path to store the image in the Environment.getExternalStorageDirectory() path and then working from there?
Also, as Robert pointed out, make sure you have write permission to external storage in your manifest.
Edit - to create directories:
String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/mvc/mvc").mkdirs();
Then you can save a file to root + "/mvc/mvc/foo.png".
Have you requested permission to write onto SD card? Add the following string to you app manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You should check if you have added the required permission android.permission-group.STORAGE to your app. Without that permission you won't be able to access anything on the SD-Card.
BTW: On the Android system I know the SD-card is mounted on /sdcard not /mnt/sdcard
I found this book to be very helpful: "Pro Android Media: Developing Graphics, Music, Video, and Rich Media Apps for Smartphones and Tablets". I noticed a part that allows saving images and stuff to the SD card.