安卓读取外部存储/storage/emulated/0/Download/函数
时间: 2024-01-24 20:03:52 浏览: 348
以下是一个示例代码,演示如何在安卓中读取外部存储的文件:
```java
import android.os.Environment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private static final String FILE_PATH = Environment.getExternalStorageDirectory().getPath() + "/Download/sample.txt";
private String readFileFromExternalStorage() {
StringBuilder stringBuilder = new StringBuilder();
try {
File file = new File(FILE_PATH);
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
// 在合适的地方调用该方法
private void readExternalStorage() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String fileContent = readFileFromExternalStorage();
// 处理文件内容
// ...
}
}
}
```
请注意,为了能够读取外部存储的文件,你需要在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
阅读全文