当前位置:首页 > 行业动态 > 正文

安卓开发存储读取图片与文字文件

安卓存储与读取图片及文字文件详解


图片存储与读取

存储位置

存储类型 路径获取方式 特点
内部存储 context.getFilesDir() 无需申请权限,数据私密性强
外部存储 Environment.getExternalStorageDirectory() 需动态申请权限,可跨应用共享(Android Q后受限)
应用专属外部存储 context.getExternalFilesDir(String type) 无需动态权限,数据卸载时自动清除

存储图片步骤

  1. 检查权限(仅外部存储需要):

    安卓开发存储读取图片与文字文件

    安卓开发存储读取图片与文字文件

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
    }
  2. 保存图片到文件

    安卓开发存储读取图片与文字文件

    // 示例:保存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();
    }

读取图片步骤

  1. 从文件创建Bitmap
    File file = new File(context.getFilesDir(), "image.png");
    if (file.exists()) {
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
        imageView.setImageBitmap(bitmap);
    }

通过MediaStore保存(兼容Android Q)

// 保存到公共图片目录
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"/>
    • Android 6.0+需动态申请:
      ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);

文件路径错误

  • 原因:混淆内部/外部存储路径,或Android Q+沙盒机制限制。
  • 解决
    • 内部存储:getFilesDir()
    • 外部存储(兼容Android Q):getExternalFilesDir(String type)
    • 公共目录(需MediaStore):MediaStore.Images.Media.EXTERNAL_CONTENT_URI

文件不存在

  • 解决:读取前检查file.exists(),或使用try-catch捕获FileNotFoundException

相关问题与解答

问题1:如何将图片保存到系统相册?

  • 解答
    1. 使用MediaStore.Images.Media.EXTERNAL_CONTENT_URI插入数据。
    2. 调用scanFile触发媒体扫描:
      sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));

问题2:如何加密存储敏感文字文件?

  • 解答
    1. 使用AES加密后存储:
      // 加密示例(需引入BouncyCastle库)
      byte[] encrypted = EncryptionUtils.encrypt("敏感数据", key);
      // 存储encrypted字节数组
    2. 或存入SQLite/Room数据库,利用数据库加密插件(如sqlcipher)。