Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 389
Moe Avatar asked Mar 28 '11 01:03

Moe


People also ask

What is getExternalStorageDirectory in android?

getExternalStorageDirectory() Return the primary shared/external storage directory. static File. getExternalStoragePublicDirectory(String type) Get a top-level shared/external storage directory for placing files of a particular type.

How do I save files on Android?

Right-click the filename, and a menu pops up that allows you to perform different operations on the file. Seeing the File in Device File Explorer. Open lets you open the file in Android Studio. Save As… lets you save the file to your file system.


1 Answers

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(); 
like image 153
debracey Avatar answered Sep 22 '22 14:09

debracey