【发布时间】:2011-08-08 13:50:38
【问题描述】:
是否可以通过编程将 sdcard 中存在的文件夹复制到存在相同 sdcard 的另一个文件夹中??
如果是这样,该怎么做?
【问题讨论】:
标签: android copy directory android-sdcard android-file
是否可以通过编程将 sdcard 中存在的文件夹复制到存在相同 sdcard 的另一个文件夹中??
如果是这样,该怎么做?
【问题讨论】:
标签: android copy directory android-sdcard android-file
该示例的改进版本:
// If targetLocation does not exist, it will be created.
public void copyDirectory(File sourceLocation , File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
// make sure the directory we plan to store the recording in exists
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create dir " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
如果传递的目标文件位于不存在的目录中,则得到更好的错误处理和更好的处理。
【讨论】:
参见示例here。 sdcard是外部存储,可以通过getExternalStorageDirectory访问。
【讨论】:
是的,这是可能的,我在我的代码中使用了以下方法。希望对你充分利用:-
public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
【讨论】:
要移动文件或目录,可以使用File.renameTo(String path)函数
File oldFile = new File (oldFilePath);
oldFile.renameTo(newFilePath);
【讨论】:
Kotlin 代码
fun File.copyFileTo(file: File) {
inputStream().use { input ->
file.outputStream().use { output ->
input.copyTo(output)
}
}
}
fun File.copyDirTo(dir: File) {
if (!dir.exists()) {
dir.mkdirs()
}
listFiles()?.forEach {
if (it.isDirectory) {
it.copyDirTo(File(dir, it.name))
} else {
it.copyFileTo(File(dir, it.name))
}
}
}
【讨论】: