将文件从目录复制到另一个目录,具有文件和目录的路径

在我的Android应用程序中,我想将文件从一个目录复制到另一个目录,我有文件filePath的路径, dirPath在必须复制文件的内容中有目录dirPath的路径。 我尝试了很多方法,但没有任何帮助,有些方法只能制作一些空的(0 kb)文件,其名称与我的文件名不同。 请帮助请:)

这是代码的一部分,如果它对你有用,我有两个按钮用于Gallery和Camera,我必须从那里选择图像

 Button btnCam = (Button) dialog.findViewById(R.id.btncamera); btnCam.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.cancel(); Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, 2500); } }); //end of camera button Button btnGal = (Button) dialog.findViewById(R.id.btngalary); btnGal.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.cancel(); Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE); } }); 

和活动结果

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); url = new String(selectedImage.toString()); //here I must copy file with path `selectedImage` and replace it in // directory with path `currentDir.hetPath()` } if (requestCode == 2500) { Bitmap photo = (Bitmap) data.getExtras().get("data"); imageView.setImageBitmap(photo); //here I must do the same thing above } } 

我找到了一些方法,在我的Activity结果中我必须调用copyFile(String, String)函数,这里是正文

 public static boolean copyFile(String from, String to) { try { File sd = Environment.getExternalStorageDirectory(); if (sd.canWrite()) { int end = from.toString().lastIndexOf("/"); String str1 = from.toString().substring(0, end); String str2 = from.toString().substring(end+1, from.length()); File source = new File(str1, str2); File destination= new File(to, str2); if (source.exists()) { FileChannel src = new FileInputStream(source).getChannel(); FileChannel dst = new FileOutputStream(destination).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); } } return true; } catch (Exception e) { return false; } } 

如果您愿意,可以在您的应用程序中包含Apache Commons I / O. 我不知道它有多大。 请参阅使用Java复制文件的标准简洁方法?

或者也许你可以下载源代码,然后选择源代码到FileUtils.copyFile()