在我的android应用程序中我想将文件从一个目录复制到另一个目录,我有文件filePath
的路径,并且在我必须复制文件的路径中有目录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
}
}
答案 0 :(得分:10)
我找到了一些方法,在我的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;
}
}
答案 1 :(得分:1)
如果您愿意,可以在您的应用中包含Apache Commons I / O.我不知道它有多大。见Standard concise way to copy a file in Java?
或许您可以下载源代码,并将源代码选择到FileUtils.copyFile()