上一篇
安卓将数据存储到文件的操作
- 行业动态
- 2025-04-23
- 3042
安卓将数据存储到文件需通过File类创建文件,选择内部存储(自动管理)或外部存储(需动态申请WRITE_PERMISSION),使用FileOutputStream写入数据,操作后关闭流并捕获IO异常,注意路径合法性和存储空间
安卓文件存储操作详解
存储类型与路径
存储类型 | 路径格式(Context 为context ) | 特点 |
---|---|---|
内部存储 | context.getFilesDir() | 应用私有,无需申请权限,卸载后数据删除 |
外部存储 | context.getExternalFilesDir(String type) | 应用私有目录(Android 10+),需动态申请WRITE_EXTERNAL_STORAGE 权限(Android 10前) |
Environment.getExternalStorageDirectory() | 公共目录(Android 10后需适配Scoped Storage) |
内部存储操作步骤
获取文件目录
File filesDir = context.getFilesDir(); // 路径:/data/data/包名/files/
创建文件并写入数据
File file = new File(filesDir, "example.txt"); try (FileOutputStream fos = new FileOutputStream(file, true)) { // true表示追加模式 String data = "Hello World "; fos.write(data.getBytes()); } catch (IOException e) { e.printStackTrace(); }
读取文件内容
try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line; while ((line = reader.readLine()) != null) { Log.d("FileContent", line); } } catch (IOException e) { e.printStackTrace(); }
外部存储操作(以Android 10+为例)
动态申请权限
<!-AndroidManifest.xml --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
// 运行时申请权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE); }
写入应用专属外部目录
File externalDir = context.getExternalFilesDir("myapp"); // 路径:/storage/emulated/0/Android/data/包名/files/myapp/ if (externalDir != null) { File file = new File(externalDir, "example.txt"); try (FileOutputStream fos = new FileOutputStream(file)) { fos.write("External Storage Data".getBytes()); } catch (IOException e) { e.printStackTrace(); } }
注意事项
Android 10+ Scoped Storage限制
- 直接访问
Environment.getExternalStorageDirectory()
可能失败,建议使用getExternalFilesDir()
或通过MediaStore
API操作公共目录。 - 若需访问任意路径,需声明
requestLegacyExternalStorage
属性(不推荐)。
- 直接访问
文件路径兼容性
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // Android 10+逻辑 } else { // 旧版本逻辑 }
异常处理
- 始终捕获
IOException
,避免因文件不存在或权限不足导致崩溃。 - 检查
File
对象是否存在(file.exists()
)及是否可读写(file.canRead()
/file.canWrite()
)。
- 始终捕获
代码示例汇总
// 内部存储写入 public void writeInternalFile(Context context, String content) { File filesDir = context.getFilesDir(); File file = new File(filesDir, "internal_example.txt"); try (FileOutputStream fos = new FileOutputStream(file, true)) { fos.write(content.getBytes()); } catch (IOException e) { e.printStackTrace(); } } // 外部存储读取(Android 10+) public String readExternalFile(Context context) { File externalDir = context.getExternalFilesDir("myapp"); if (externalDir == null) return null; File file = new File(externalDir, "example.txt"); try (BufferedReader reader = new BufferedReader(new FileReader(file))) { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); return null; } }
相关问题与解答
问题1:如何在Android 11中保存图片到公共相册?
解答:
Android 11(API 30)后,直接访问公共目录受限,需使用MediaStore
API:
ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Camera"); // 保存到公共相册路径 values.put(MediaStore.Images.Media.IS_PENDING, 1); // 标记为待处理 Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); if (uri != null) { // 写入图片数据到uri对应的输出流 contentResolver.openOutputStream(uri).close(); // 释放IS_PENDING标记 }
问题2:如何判断文件是否存在并可读写?
解答:
使用File
类的以下方法:
exists()
:检查文件是否存在。canRead()
:检查是否可读。canWrite()
:检查是否可写。
示例:File file = new File("/path/to/file"); if (file.exists() && file.canRead() && file.canWrite()) { // 文件存在且可读写 } else { // 处理异常情况 }