Вывести список файлов из определенной папки (внутреннее хранилище) и переместить выбранный файл в другую папку - PullRequest
0 голосов
/ 28 января 2019

Во внутренней памяти есть папка «Проекты», я хочу перечислить все содержимое, имеющееся в папке проекта, в виде списка, затем выбранный пользователем файл следует переименовать и скопировать в другую папку, которая называется «Новые проекты».шаг за шагом в Android.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub

    switch (requestCode) {
        case 7:
            if (resultCode == RESULT_OK) {
                String PathHolder = data.getData().getPath();
                Toast.makeText(MockLocation.this, PathHolder, Toast.LENGTH_LONG).show();

                String targetLocation = "/document/primary:HUACENAV/GnssServer/";


                String sourcePath = Environment.getExternalStorageDirectory().getAbsolutePath() + PathHolder;
                File source = new File(sourcePath);

                String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + targetLocation;
                File destination = new File(destinationPath);

                copyFileOrDirectory(sourcePath,destinationPath);


            }
            break;
    }
}



public static void copyFileOrDirectory(String srcDir, String dstDir) {

    try {
        File src = new File(srcDir);
        File dst = new File(dstDir, src.getName());

        if (src.isDirectory()) {

            String files[] = src.list();
            int filesLength = files.length;
            for (int i = 0; i < filesLength; i++) {
                String src1 = (new File(src, files[i]).getPath());
                String dst1 = dst.getPath();
                copyFileOrDirectory(src1, dst1);

            }
        } else {
            copyFile(src, dst);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void copyFile(File sourceFile, File destFile) throws IOException {
    if (!destFile.getParentFile().exists())
        destFile.getParentFile().mkdirs();

    if (!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;

    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}
...