android外部存储写入和读取
时间: 2024-01-30 08:02:42 浏览: 120
在Android中,可以使用以下代码进行外部存储的写入和读取:
写入文件:
```java
String fileName = "myfile.txt";
String data = "This is the content of my file.";
// 获取外部存储目录
File externalStorageDir = Environment.getExternalStorageDirectory();
// 创建文件
File file = new File(externalStorageDir, fileName);
try {
// 创建文件输出流
FileOutputStream outputStream = new FileOutputStream(file);
// 写入数据
outputStream.write(data.getBytes());
// 关闭流
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
```
读取文件:
```java
String fileName = "myfile.txt";
// 获取外部存储目录
File externalStorageDir = Environment.getExternalStorageDirectory();
// 创建文件
File file = new File(externalStorageDir, fileName);
try {
// 创建文件输入流
FileInputStream inputStream = new FileInputStream(file);
// 读取数据
byte[] buffer = new byte[1024];
int length = inputStream.read(buffer);
// 关闭流
inputStream.close();
// 转换为字符串
String data = new String(buffer, 0, length);
} catch (IOException e) {
e.printStackTrace();
}
```
需要注意的是,为了在Android设备上访问外部存储,需要在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
阅读全文