是否可以以编程方式将 sdcard 中存在的文件夹复制到存在相同 sdcard 的另一个文件夹?
如果是这样,该怎么做?
是否可以以编程方式将 sdcard 中存在的文件夹复制到存在相同 sdcard 的另一个文件夹?
如果是这样,该怎么做?
该示例的改进版本:
// 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();
}
}
如果传递的目标文件位于不存在的目录中,则可以获得更好的错误处理和更好的处理。
请参阅此处的示例。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);
科特林代码
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))
}
}
}