android:文件复制:选择图片并复制并添加到相册

一,代码:

xml上只有一个按钮

java代码:

package com.example.okdemo1.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.okdemo1.R;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;

public class FileActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_CHOOSE = 23;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_file);

        //给按钮增加点击事件
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //请求权限
                selectFile();
            }
        });
    }

    //选择文件,完整版时应该添加请求相机\存储权限
    private void selectFile(){
        //选择文件
        Matisse.from(FileActivity.this)
                .choose(MimeType.of(MimeType.JPEG, MimeType.WEBP, MimeType.PNG, MimeType.GIF))//图片类型
                .countable(true)//true:选中后显示数字;false:选中后显示对号
                .maxSelectable(5)//可选的最大数
                .capture(true)//选择照片时,是否显示拍照
                .captureStrategy(new CaptureStrategy(true, "com.example.okdemo1.fileprovider"))//参数1 true表示拍照存储在共有目录,false表示存储在私有目录;参数2与 AndroidManifest中authorities值相同,用于适配7.0系统 必须设置
                .imageEngine(new GlideEngine())//图片加载引擎
                .forResult(REQUEST_CODE_CHOOSE);//
    }

    //选择图片后回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("执行到了onActivityResult:");
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {

            List<String> paths = Matisse.obtainPathResult(data);
            for (int i = 0; i < paths.size(); i++) {
                String onePath = paths.get(i);
                System.out.println("源文件名:" + onePath);

                File file = new File(onePath);
                String fileName = file.getName();
                int pos = fileName.lastIndexOf(".");
                String dstPath = "";
                //有扩展名时的处理
                if (pos > 0 && pos < fileName.length() - 1) {
                    String ext = fileName.substring(pos + 1);
                    String fileNameWithoutExt = fileName.substring(0, pos);
                    System.out.println("文件扩展名: " + ext);
                    String pathWithoutExt = file.getParent() + File.separator + fileNameWithoutExt;
                    dstPath = pathWithoutExt+"_2."+ext;
                } else {   //无扩展名时的处理
                    dstPath = onePath+"_2";
                }
                System.out.println("目标文件名:"+dstPath);

                copyFile(onePath, dstPath);
                //判断文件是否存在
                Path path = Paths.get(dstPath);
                boolean exists = Files.exists(path);
                System.out.println("文件复制后新文件是否存在:"+exists);
                //显示到相册
                saveToGallery(this, dstPath);
            }
        }
    }

    //复制文件
    public void copyFile(String srcPath, String dstPath) {
        try {
                Files.copy(Paths.get(srcPath), Paths.get(dstPath), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //把图片文件路径添加到图库
    public void saveToGallery(Context context, String path) {
        File file = new File(path);
        String fileName =  file.getName();
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
    }

}

说明:权限的设置和动态请求等请自行添加

二,测试效果:

posted @ 2025-06-07 10:50  刘宏缔的架构森林  阅读(35)  评论(0)    收藏  举报