[英]Android how to use Environment.getExternalStorageDirectory()
我如何使用Environment.getExternalStorageDirectory()
从 SD 卡读取存储的图像,或者有更好的方法吗?
Environment.getExternalStorageDirectory().getAbsolutePath()
Gives you the full path the SDCard.为您提供 SDCard 的完整路径。 You can then do normal File I/O operations using standard Java.然后,您可以使用标准 Java 执行正常的文件 I/O 操作。
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 eg my Motorola razr maxx, as it has 2 cards /mnt/sdcard and /mnt/sdcard-ext - for internal and external SD cards respectfully.但是请记住, getExternalStorageDirectory()在某些手机上无法正常工作,例如我的摩托罗拉 razr maxx,因为它有 2 张卡 /mnt/sdcard 和 /mnt/sdcard-ext - 分别用于内部和外部 SD 卡。 You will be getting the /mnt/sdcard only reply every time.您每次只会收到 /mnt/sdcard 回复。 Google must provide a way to deal with such a situation.谷歌必须提供一种方法来处理这种情况。 As it renders many SD card aware apps (ie card backup) failing miserably on these phones.因为它使许多 SD 卡感知应用程序(即卡备份)在这些手机上惨遭失败。
As described in Documentation Environment.getExternalStorageDirectory() :如文档Environment.getExternalStorageDirectory() 中所述:
Environment.getExternalStorageDirectory() Return the primary shared/external storage directory. Environment.getExternalStorageDirectory()返回主共享/外部存储目录。
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!";
}
要获取目录,您可以使用以下代码:
File cacheDir = new File(Environment.getExternalStorageDirectory() + File.separator + "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.