1、使用channel高效拷贝文件:
[Java] 纯文本查看 复制代码 public static void copyFileUsingFileChannels(File source, File dest)
throws IOException {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
Log.e("ch_test", "---copy file success >>> " + dest.getAbsolutePath());
} finally {
inputChannel.close();
outputChannel.close();
}
}
2、拷贝文件夹及其子文件:(递归思想)
[Java] 纯文本查看 复制代码 public static boolean copyFolder(String oldPath, String newPath) {
try {
File newFile = new File(newPath);
if (!newFile.exists()) {
if (!newFile.mkdirs()) {
Log.e("--Method--", "copyFolder: cannot create directory.");
return false;
}
}
File oldFile = new File(oldPath);
String[] files = oldFile.list();
File temp;
for (String file : files) {
if (oldPath.endsWith(File.separator)) {
temp = new File(oldPath + file);
} else {
temp = new File(oldPath + File.separator + file);
}
if (temp.isDirectory()) { //如果是子文件夹
copyFolder(oldPath + "/" + file, newPath + "/" + file);
} else if (!temp.exists()) {
Log.e("--Method--", "copyFolder: oldFile not exist.");
return false;
} else if (!temp.isFile()) {
Log.e("--Method--", "copyFolder: oldFile not file.");
return false;
} else if (!temp.canRead()) {
Log.e("--Method--", "copyFolder: oldFile cannot read.");
return false;
} else {
FileInputStream fileInputStream = new FileInputStream(temp);
FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
byte[] buffer = new byte[1024];
int byteRead;
while ((byteRead = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, byteRead);
}
fileInputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
}
/* 如果不需要打log,可以使用下面的语句
if (temp.isDirectory()) { //如果是子文件夹
copyFolder(oldPath + "/" + file, newPath + "/" + file);
} else if (temp.exists() && temp.isFile() && temp.canRead()) {
FileInputStream fileInputStream = new FileInputStream(temp);
FileOutputStream fileOutputStream = new FileOutputStream(newPath + "/" + temp.getName());
byte[] buffer = new byte[1024];
int byteRead;
while ((byteRead = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, byteRead);
}
fileInputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
}
*/
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
|