android12 sdcard读写文件的示例
时间: 2024-04-29 18:25:09 浏览: 7
Sure, here's an example code snippet for reading and writing files to the SD card in Android 12:
```
// Check if we can access the external storage
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// Get the root directory of the SD card
File sdcard = Environment.getExternalStorageDirectory();
// Create a new file object for the file we want to read/write
File file = new File(sdcard, "example.txt");
try {
// Open a file output stream for writing to the file
FileOutputStream fos = new FileOutputStream(file);
// Write some data to the file
fos.write("Hello world!".getBytes());
// Close the output stream
fos.close();
// Open a file input stream for reading from the file
FileInputStream fis = new FileInputStream(file);
// Read the data from the file
byte[] data = new byte[(int) file.length()];
fis.read(data);
// Convert the data to a string and print it
String str = new String(data, "UTF-8");
System.out.println(str);
// Close the input stream
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("External storage not available");
}
```
I hope this helps! Let me know if you have any more questions.