内部存储中有一个名为“项目”的文件夹,我想在列表视图中列出项目文件夹中所有可用的内容,然后用户选择的文件应重命名并复制到另一个名为“新项目”的文件夹中。请解释在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();
}
}
}