将内部存储的文件复制到相册

214 阅读2分钟

AndroidManifest.xml添加权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

申请外部存储读写权限

private void requestStoragePermission() {
    // 检查是否已经被授予权限
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "存储权限已被允许");
    } else {
        Log.d(TAG, "申请存储权限");
        // 申请存储权限
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, GET_STORAGE_CODE);
    }
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    // 检查 requestCode 是否是我们之前定义的 GET_STORAGE_CODE
    if (requestCode == GET_STORAGE_CODE) {
        // 检查用户是否授予了存储权限
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 用户授予了存储权限
            Log.d(TAG, "存储权限已被授予");
        } else {
            // 用户拒绝了存储权限
            Log.d(TAG, "存储权限被拒绝");
            // 在这里您可以提供一些用户提示,或者采取其他措施来处理权限被拒绝的情况
        }
    }
}

编码

public void copyVideoToGallery(Context context, String sourceFilePath) {
        File sourceFile = new File(sourceFilePath);
        
        //检查传入的文件路径sourceFilePath是否真实存在
        if (!sourceFile.exists()) {
            Log.d(TAG, "!sourceFile.exists():" + !sourceFile.exists());
            return;
        }
        
     //相册路径
     File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
     File storageDir = new File(path,appName);
        // 创建目标文件夹
        if (!storageDir.exists()) {
            storageDir.mkdirs();
        }
        // 创建目标文件
        File destinationFile = new File(storageDir, sourceFile.getName());
        try {
            FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel();
            FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel();
            destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
            sourceChannel.close();
            destinationChannel.close();
            // 添加文件到相册
            addVideoToGallery(context, destinationFile.getAbsolutePath());
            Log.d(TAG, "video copied to gallery:" + destinationFile.getAbsolutePath());
        } catch (IOException e) {
            Log.d(TAG, "copyVideoToGallery error:" + e);
        }
    }

    private void addVideoToGallery(Context context, String videoFilePath) {
        MediaScannerConnection.scanFile(context, new String[]{videoFilePath}, new String[]{"video/mp4"},
                (path, uri) -> Log.d(TAG, "Video scanned and added to gallery:" + path));
    }

工具类


package com.yimturm.camera.utils;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class VideoSave {

    private static final String TAG = "VideoSave";
    private static final String appName = "cameraFile"; // 请替换成你的应用名字

    public static void copyVideoToGallery(Context context, String sourceFilePath) {
        File sourceFile = new File(sourceFilePath);

        // 检查传入的文件路径 sourceFilePath 是否真实存在
        if (!sourceFile.exists()) {
            Log.d(TAG, "!sourceFile.exists():" + !sourceFile.exists());
            return;
        }

        // 根据 Android 版本选择保存路径
        File destinationFile;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            // Android 10 之前,保存到内部存储文件夹
            File appSpecificDir = context.getExternalFilesDir(null);
            File storageDir = new File(appSpecificDir, appName);
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }
            destinationFile = new File(storageDir, sourceFile.getName());
        } else {
            // Android 10 及以上,保存到相册
            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
            File storageDir = new File(path, appName);
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }
            destinationFile = new File(storageDir, sourceFile.getName());
        }

        try {
            FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel();
            FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel();
            destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
            sourceChannel.close();
            destinationChannel.close();
            // 添加文件到相册
            addVideoToGallery(context, destinationFile.getAbsolutePath());
        } catch (IOException e) {
            Log.d(TAG, "copyVideoToGallery error:" + e);
        }
    }

    private static void addVideoToGallery(Context context, String videoFilePath) {
        MediaScannerConnection.scanFile(context, new String[]{videoFilePath}, new String[]{"video/mp4"},
                (path, uri) -> Log.d(TAG, "Video scanned and added to gallery:" + path));
    }
}



使用例子:  

VideoSave.copyVideoToGallery(Constant.instance, "/data/data/com.yimturm.camera/files/IOTDCC-509687-PPVKX_1700019964255.mp4");

或者

// 获取内部文件目录
File internalFilesDir = new File(getFilesDir(Constant.instance));
// 构建内部存储路径
String path = internalFilesDir.getAbsolutePath() + File.separator + did + "_" + System.currentTimeMillis() + ".prv";
VideoSave.copyVideoToGallery(Constant.instance,path);