首页 > 解决方案 > 如何在 Android Studio 的 Scoped Storage 中移动或重命名 Android 11 中的图像、视频文件

问题描述

我想移动和重命名图像文件,这个图像文件不是我的应用程序创建的,所以我可以在范围存储中移动或重命名 android 11 中的图像文件。

这是 android api 11 的重命名方法。

但它没有用。


        File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "newFolder");

        if (!dir.exists()) {
            dir.mkdir();
        }
        File file = new File(model.getPicturePath());


        long mediaID = getFilePathToMediaID(new File(file.getAbsolutePath()).getAbsolutePath(), this);
        Uri utiOne =ContentUris.withAppendedId(MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL),mediaID);

        String path = dir.getAbsolutePath()+File.separator+model.getPictureName();
        Toast.makeText(this, "" +model.getPicturePath(), Toast.LENGTH_SHORT).show();

        ContentValues cv = new ContentValues();
//        cv.put(MediaStore.Images.Media.BUCKET_DISPLAY_NAME,".newFolder");
//        cv.put(MediaStore.Images.Media.RELATIVE_PATH,Environment.DIRECTORY_PICTURES+File.separator+".newFolder");
        cv.put(MediaStore.Images.Media.DATA,path);
//        cv.put(MediaStore.Images.Media._ID,model.getPictureId());

        getContentResolver().update(utiOne,cv,null);

标签: androidandroid-studiomediastorescoped-storage

解决方案


要重命名文件,您可以使用以下代码::

File dir = Environment.getExternalStorageDirectory();
if(dir.exists()){
    File from = new File(dir,"from.png");
    File to = new File(dir,"to.png");
     if(from.exists())
        from.renameTo(to);
}

要将文件从一个文件夹移动到另一个文件夹:

检查您是否已在 manifeast.xml 文件中授予权限

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

移动文件::

private void moveFile(String inputPath, String inputFile, String outputPath) {

    InputStream in = null;
    OutputStream out = null;
    try {

        //create output directory if it doesn't exist
        File dir = new File (outputPath); 
        if (!dir.exists())
        {
            dir.mkdirs();
        }


        in = new FileInputStream(inputPath + inputFile);        
        out = new FileOutputStream(outputPath + inputFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;

            // write the output file
            out.flush();
        out.close();
        out = null;

        // delete the original file
        new File(inputPath + inputFile).delete();  


    } 

         catch (FileNotFoundException fnfe1) {
        Log.e("tag", fnfe1.getMessage());
    }
          catch (Exception e) {
        Log.e("tag", e.getMessage());
    }

}

推荐阅读