How can i use Environment.getExternalStorageDirectory()
to read a a stored image from the SD card or is there a better way to do it?
Environment.getExternalStorageDirectory().getAbsolutePath()
Gives you the full path the SDCard. You can then do normal File I/O operations using standard Java.
Here's a simple example for writing a file:
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
// Not sure if the / is on the path or not
File f = new File(baseDir + File.separator + fileName);
f.write(...);
f.flush();
f.close();
Edit:
Oops - you wanted an example for reading ...
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "myFile.txt";
// Not sure if the / is on the path or not
File f = new File(baseDir + File.Separator + fileName);
FileInputStream fiStream = new FileInputStream(f);
byte[] bytes;
// You might not get the whole file, lookup File I/O examples for Java
fiStream.read(bytes);
fiStream.close();
Have in mind though, that getExternalStorageDirectory() is not going to work properly on some phones e.g. my Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully. You will be getting the /mnt/sdcard only reply every time. Google must provide a way to deal with such a situation. As it renders many SD card aware apps (i.e card backup) failing miserably on these phones.
Environment.getExternalStorageDirectory().getAbsolutePath();
–
Miner As described in Documentation Environment.getExternalStorageDirectory() :
Environment.getExternalStorageDirectory() Return the primary shared/external storage directory.
This is an example of how to use it reading an image :
String fileName = "stored_image.jpg";
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String pathDir = baseDir + "/Android/data/com.mypackage.myapplication/";
File f = new File(pathDir + File.separator + fileName);
if(f.exists()){
Log.d("Application", "The file " + file.getName() + " exists!";
}else{
Log.d("Application", "The file no longer exists!";
}
getExternalStorageDirectory()
we can create new directory in user preferred storage (which is generally internal memory). so, what happens if the default storage has been set to External memory
and it's not readable/writable? Does this throw exception? or it will automatically create in Internal storage
? –
Gallopade To get the directory, you can use the code below:
File cacheDir = new File(Environment.getExternalStorageDirectory() + File.separator + "");
© 2022 - 2024 — McMap. All rights reserved.
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
– Wary