Скопируйте файлы из папки SD-карты в другую папку SD-карты

Можно ли программно скопировать папку, находящуюся на SD-карте, в другую папку на той же SD-карте ??

Если да, то как это сделать?


person Siva Kumar    schedule 19.04.2011    source источник


Ответы (5)


Улучшенная версия этого примера:

// 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();
    }
}

Улучшена обработка ошибок и улучшена обработка, если переданный целевой файл находится в несуществующем каталоге.

person Ne0    schedule 21.06.2012


да, это возможно, и я использую метод ниже в моем коде. Надежда на полное использование для вас: -

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();
    }

}
person duggu    schedule 07.02.2013

Для перемещения файлов или каталогов вы можете использовать функцию File.renameTo(String path)

File oldFile = new File (oldFilePath);
oldFile.renameTo(newFilePath);
person Amjad Abu Saa    schedule 20.05.2013
comment
Это удалит файл из исходного каталога. - person Ankit; 14.11.2013

Код Котлина

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))
        }
    }
}
person Vlad    schedule 18.04.2020