Android如何使用Environment.getExternalStorageDirectory()

时间:2011-03-28 01:06:37

标签: android sd-card

如何使用Environment.getExternalStorageDirectory()从SD卡读取存储的图像,或者有更好的方法吗?

4 个答案:

答案 0 :(得分:79)

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();

答案 1 :(得分:36)

请记住, getExternalStorageDirectory()在某些手机上无法正常工作,例如我的摩托罗拉razr maxx,因为它有2张卡/ mnt / sdcard和/ mnt / sdcard-ext - 分别用于内部和外部SD卡。你每次都会得到/ mnt / sdcard回复。谷歌必须提供一种处理这种情况的方法。因为它使许多SD卡识别应用程序(即卡片备份)在这些手机上惨遭失败。

答案 2 :(得分:0)

如文档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!";
         }

答案 3 :(得分:0)

要获取目录,可以使用以下代码:

File cacheDir = new File(Environment.getExternalStorageDirectory() + File.separator + "");