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