Android 11读取写入 存储卡 文件 代码示例
时间: 2024-09-30 11:05:30 浏览: 30
在Android 11及以上版本,由于安全性和隐私政策的变化,直接读写外部存储(如SD卡)变得更为复杂。你需要申请特定的权限,并且只能在文件路径位于Android外部存储目录的子目录下。以下是读取和写入文件的基本示例:
首先,在AndroidManifest.xml中添加读写外部存储权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
然后在运行时请求权限:
```java
private void requestStoragePermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
int grantResult = ActivityCompat.checkSelfPermission(this, permissions[0]);
if (grantResult != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, permissions, REQUEST_EXTERNAL_STORAGE);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_EXTERNAL_STORAGE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 用户已授予权限,可以继续操作
} else {
// 没有得到权限,提示用户
}
}
}
```
接下来,我们可以使用`Environment.getExternalStorageDirectory()`获取外部存储根目录,然后构造完整的文件路径:
```java
File externalStorageDir = Environment.getExternalStorageDirectory();
String path = externalStorageDir.getAbsolutePath() + "/YourDirectoryName/";
File file = new File(path, "your_file_name.txt");
// 读取文件
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
Log.d("TAG", line);
}
} catch (IOException e) {
e.printStackTrace();
}
// 写入文件
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) {
bw.write("Data to write");
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
```
请注意,上述代码仅适用于Android 11及更高版本。对于Android 10(API Level 29)及以下版本,你需要在运行时检查并处理`ACTION_EXTERNAL_STORAGE`的`ACTION_GET_CONTENT`请求。
阅读全文