高效拷贝文件和文件夹
1、使用channel高效拷贝文件: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、拷贝文件夹及其子文件:(递归思想)
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;
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;
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;
}
}
和 okio 比如何? 还是说这个只是 api 上的简单呢
不明觉厉 占用系统资源厉害吗 yizems 发表于 2020-11-11 16:01
和 okio 比如何? 还是说这个只是 api 上的简单呢
具体没测试,okio也是基于java io/nio。感觉看具体场景吧,和内存有关系吧。 鸭子咯咯哒~ 发表于 2020-11-11 16:33
占用系统资源厉害吗
尽管绕过了cpu申请,还是需要看拷贝文件的大小及数量,以及当时机器的内存性能。 jiushu52 发表于 2020-11-11 16:04
不明觉厉,高效的传输这个是自己做一个代码?一个程序?
对,自己在java平台做一个。如果能够在c++层面实现应该效率会更高一些。
页:
[1]