[英]Create a new File on SD card from uri?
我從大量的Intent中獲取多個uri。ACTION_SEND_MULTIPLEintent
我要做的就是將這些文件復制到新位置“ / sdcard / BACKUP /”,我已經嘗試了好幾個小時了,但沒有解決辦法
這是代碼:
ArrayList<Uri> imageUris = null;
if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
String root = Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
File createDir = new File(root+"BACKUP"+File.separator);
if(!createDir.exists()) {
createDir.mkdir();
}
for (Uri uri : imageUris){
File file = new File(uri.getPath());
File newfile = new File(root + "BACKUP" + File.separator + uri.toString() +".jpg" );
copyFile(file,newfile);
}
private void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
我收到java.io.Filenotfound異常
您只需要WRITE_EXTERNAL_STORAGE
權限即可
sourceFile.renameTo(destFile);
renameTo
的文檔說
將此文件重命名為newPath。 文件和目錄均支持此操作
你可以在這里找到
問題是初始化源文件
這是有效的:
File file = new File(getPath(uri));
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
謝謝大家的支持
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.