android - 如何在 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);
解决方案
要重命名文件,您可以使用以下代码::
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());
}
}
推荐阅读
- python - 无论如何要在本地保存从网站链接自动下载的文件?
- r - 基于当前上一个和下一个值的新变量的 R 规则
- python - 为什么 Tkinter 不调用绑定到根窗口的函数?
- python - 为什么它给我 TypeError: Expected cv::UMat for argument 'src'?
- python-3.x - 如何通过索引名称访问数据框中新添加(生成)的行?
- java - Java8 时间库无法正确解释 BST 时区
- arrays - 用于在 Powrpoint 演示文稿中选择幻灯片的输入框。(几乎完成)
- javascript - 如何计算 div 类的费率?
- css - CSS 样式不适用于已经存在的组件/正文标签
- java - 模拟实例方法