Android如何使用Environment.getExternalStorageDirectory()
我如何使用Environment.getExternalStorageDirectory()
从SD卡读取已存储的图像,或者有更好的方法来完成它吗?
Environment.getExternalStorageDirectory().getAbsolutePath()
为您提供SDCard的完整路径。 然后,您可以使用标准Java执行正常的文件I / O操作。
以下是编写文件的一个简单示例:
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();
编辑:
哎呀 - 你想要一个阅读的例子...
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();
请记住, getExternalStorageDirectory()无法在某些电话上正常工作,例如我的摩托罗拉razr maxx,因为它有2个卡/ mnt / sdcard和/ mnt / sdcard-ext - 分别用于内部和外部SD卡。 您将获得/ mnt / sdcard每次只回复。 Google必须提供一种方法来处理这种情况。 因为它会使许多SD卡感知应用程序(即卡备份)在这些电话上失败。
如文档Environment.getExternalStorageDirectory()中所述:
Environment.getExternalStorageDirectory()返回主共享/外部存储目录。
这是一个如何使用它读取图像的例子:
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!";
}
链接地址: http://www.djcxy.com/p/90819.html
上一篇: Android how to use Environment.getExternalStorageDirectory()
下一篇: How to enable HTTP response caching in the DownloadManager?