Можно ли программно скопировать папку, находящуюся на SD-карте, в другую папку на той же SD-карте ??
Если да, то как это сделать?
Можно ли программно скопировать папку, находящуюся на SD-карте, в другую папку на той же SD-карте ??
Если да, то как это сделать?
Улучшенная версия этого примера:
// 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();
}
}
Улучшена обработка ошибок и улучшена обработка, если переданный целевой файл находится в несуществующем каталоге.
См. пример здесь. SD-карта является внешним хранилищем, поэтому вы можете получить к ней доступ через 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))
}
}
}