的Andr​​oid如何使用Environment.getExternalStorageDirectory()如何使用、oid、Andr、Environment

2023-09-11 11:18:52 作者:你若安好,便是晴天霹雳

我如何使用 Environment.getExternalStorageDirectory()从SD卡读取AA存储的图像或是否有更好的方法来做到这一点?

解决方案

  Environment.getExternalStorageDirectory()。getAbsolutePath()
 

为您提供了完整路径的SD卡。然后,您可以使用标准的Java做正常的文件I / O操作。

下面是一个简单的例子,写入一个文件:

 字符串BASEDIR = Environment.getExternalStorageDirectory()getAbsolutePath()。
字符串文件名=myfile.txt的;

//不知道的/是路径或不
文件F =新的文件(BASEDIR +文件分割符+文件名);
f.write(...);
f.flush();
f.close();
 

编辑:

抱歉 - 你想一个例子阅读...

 字符串BASEDIR = Environment.getExternalStorageDirectory()getAbsolutePath()。
字符串文件名=myfile.txt的;

//不知道的/是路径或不
文件F =新的文件(BASEDIR +文件分割符+文件名);
的FileInputStream fiStream =新的FileInputStream(F);

byte []的字节数;

//你可能无法得到整个文件,对Java查找文件I / O的例子
fiStream.read(字节);
fiStream.close();
 

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?

解决方案

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