首页 > 解决方案 > 列出特定文件夹(内部存储)中的文件并将所选文件移动到另一个文件夹

问题描述

内部存储中有一个名为“Projects”的文件夹,我想在列表视图中列出项目文件夹中可用的所有内容,然后用户选择的文件应重命名并复制到另一个名为“New Projects”的文件夹。请逐步解释在安卓。

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

标签: androidandroid-fileinternal-storage

解决方案


推荐阅读