将文件夹的内容复制到android中的其他文件夹 [英] Copy Content of Folder to other Folder in android
本文介绍了将文件夹的内容复制到android中的其他文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将目录的所有内容(不包括父项)复制到android中的另一个目录.当我使用以下代码时,我复制了源父项和内容,我只想复制内容.我得到了文件/Tmp/内容,我想像这样复制文件/内容
How to copy all contents of Directory (not including Parent) to another directory in android.When I use below code I copyed source parent and contents,I wantto copy only contents. I got Files/Tmp/Contens, I want to copy like this Files/Contents
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();
}
}
}
推荐答案
使用FileUtils库
Use FileUtils library
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();
}
这篇关于将文件夹的内容复制到android中的其他文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文