我该如何使用
Environment.getExternalStorageDirectory()
方法读取存储在SD卡中的图像?或者是否有更好的方式实现呢?Environment.getExternalStorageDirectory().getAbsolutePath()
这个方法可以给你SD卡的完整路径,然后你就可以使用标准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()在某些手机上无法正常工作,例如我的Motorola razr maxx,它有两个卡片/mnt/sdcard和/mnt/sdcard-ext - 分别用于内部和外部SD卡。你每次都会得到/mnt/sdcard的回复。Google必须提供一种处理这种情况的方法。因为这使得许多SD卡感知应用程序(即卡备份)在这些手机上失败。
Environment.getExternalStorageDirectory().getAbsolutePath();
。 - Moeez如文档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!";
}
getExternalStorageDirectory()
我们可以在用户首选存储(通常是内部存储器)中创建新目录。那么,如果默认存储已设置为“外部存储器”,但它不可读/写,会发生什么?这会抛出异常吗?还是它会自动创建在“内部存储器”中? - S.R要获取目录,您可以使用以下代码:
File cacheDir = new File(Environment.getExternalStorageDirectory() + File.separator + "");
Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
- whlk