Android 保存文件demo
时间: 2024-11-05 20:11:08 浏览: 14
Android 保存文件通常涉及到两个关键步骤:获取存储权限和实际写入文件。这里有一个简单的示例演示如何在Android应用中读取并写入文件:
```java
// 1. 请求存储权限 (如果尚未请求)
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
} else {
// 如果已授权,可以继续操作
}
// 2. 获取外部存储目录 (Environment.getExternalStorageDirectory())
FileOutputStream outputStream = null;
try {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "example.txt");
FileOutputStream fos = openFileOutput(file.getName(), MODE_PRIVATE);
outputStream = fos;
// 写入数据
byte[] data = "这是要保存的数据".getBytes();
outputStream.write(data);
outputStream.flush(); // 确保数据写入
Log.d("SaveFile", "文件保存成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 3. 可选的:检查文件是否已保存并读取(用于测试)
try {
FileInputStream fis = openFileInput(file.getName());
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringBuilder contentBuilder = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
contentBuilder.append(line);
}
String savedContent = contentBuilder.toString();
Log.d("SaveFile", "保存的内容: " + savedContent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
阅读全文