如何将目录的所有内容(不包括父项)复制到android中的另一个目录。当我使用以下代码时,我复制了源父项和内容,我只想复制内容。我得到了文件/ Tmp /内容,我想像这样复制文件/内容
File src = new File(context.getExternalFilesDir(null).getAbsolutePath(), "Tmp");
File dir = new File(context.getExternalFilesDir(null).getAbsolutePath(), "Files");
try {
Utils.copyFileOrDirectory(src.getAbsolutePath(),dir.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
复制文件
public static void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
答案 0 :(得分:1)
//try this...
String sourcePath =
Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/folder_name1";
File source = new File(sourcePath);
String destinationPath =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/folder_name2";
File destination = new File(destinationPath);
try
{
FileUtils.copyFile(source, destination);
}
catch (IOException e)
{
e.printStackTrace();
}
答案 1 :(得分:1)
使用FileUtils库
File src = new File(context.getExternalFilesDir(null).getAbsolutePath(), "Tmp");
File dir = new File(context.getExternalFilesDir(null).getAbsolutePath(), "Files");
try {
FileUtils.copyDirectory(src,dir);
} catch (IOException e) {
e.printStackTrace();
}