存储类型 | 路径获取方式 | 特点 |
---|---|---|
内部存储 | context.getFilesDir() | 无需申请权限,数据私密性强 |
外部存储 | Environment.getExternalStorageDirectory() | 需动态申请权限,可跨应用共享(Android Q后受限) |
应用专属外部存储 | context.getExternalFilesDir(String type) | 无需动态权限,数据卸载时自动清除 |
检查权限(仅外部存储需要):
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE); }
保存图片到文件:
// 示例:保存Bitmap到内部存储 File file = new File(context.getFilesDir(), "image.png"); try (FileOutputStream fos = new FileOutputStream(file)) { bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); } catch (IOException e) { e.printStackTrace(); }
File file = new File(context.getFilesDir(), "image.png"); if (file.exists()) { Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); imageView.setImageBitmap(bitmap); }
// 保存到公共图片目录 ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DISPLAY_NAME, "image.png"); values.put(MediaStore.Images.Media.MIME_TYPE, "image/png"); Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); try (OutputStream os = context.getContentResolver().openOutputStream(uri)) { bitmap.compress(Bitmap.CompressFormat.PNG, 100, os); }
// 示例:保存字符串到外部存储 File file = new File(Environment.getExternalStorageDirectory(), "data.txt"); try (FileOutputStream fos = new FileOutputStream(file); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos))) { writer.write("Hello World!"); writer.newLine(); // 写入换行符 } catch (IOException e) { e.printStackTrace(); }
// 示例:读取外部存储的文本文件 File file = new File(Environment.getExternalStorageDirectory(), "data.txt"); if (file.exists()) { try (FileInputStream fis = new FileInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(fis))) { String line; while ((line = reader.readLine()) != null) { Log.d("FileContent", line); } } catch (IOException e) { e.printStackTrace(); } }
操作 | 输入流/输出流 | 适用场景 |
---|---|---|
写入文本 | FileOutputStream + BufferedWriter | 需要控制编码或换行时 |
读取文本 | FileInputStream + BufferedReader | 按行读取或处理编码时 |
写入二进制 | FileOutputStream | 图片、音频等非文本文件 |
读取二进制 | FileInputStream | 图片、音频等非文本文件 |
AndroidManifest.xml
中声明权限,或未动态申请。Manifest
中添加: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
getFilesDir()
getExternalFilesDir(String type)
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
file.exists()
,或使用try-catch
捕获FileNotFoundException
。MediaStore.Images.Media.EXTERNAL_CONTENT_URI
插入数据。scanFile
触发媒体扫描: sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
// 加密示例(需引入BouncyCastle库) byte[] encrypted = EncryptionUtils.encrypt("敏感数据", key); // 存储encrypted字节数组
sqlcipher
)。