目录
中有一个图像文件
。如何将这个图像文件
复制
到刚刚创建的另一个目录
中?这两个目录
在设备的同一个内部存储
上:)
最佳答案
您可以使用这些功能。如果您传入文件,第一个将复制包含所有子项或单个文件的整个目录。第二个仅对文件有用,并为第一个中的每个文件调用。
另请注意,您需要具有执行此操作的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
函数:
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();
}
}
}
关于android - 如何以编程方式将文件复制到另一个目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29867121/