Android how to use Environment.getExternalStorageDirectory()
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?
Solution 1:
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();
Solution 2:
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.
Solution 3:
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!";
}