FileChannel管道流复制文件是基于nio的传输方式。速度上有30%的提升。其次在我的项目中使用传统FileOutputStream方式,在复制大文件时。进度打印出现迟滞。综合这两点选择使用FileChannel方案。本文章是简单使用多线程方式实现,个人测试文件读写在多线程下比单线程快4倍,有参考的小伙伴使用的话 还是最好使用线程池进行处理性能上的优化。
public class CopyPasteUtil {
private static long dirSize = 0;// 文件夹总体积
private static long hasReadSize = 0;// 已复制的部分,体积
private static CopyProgressDialog progressDialog;// 进度提示框
private static Thread copyFileThread;
private static Runnable run = null;
private static FileInputStream fileInputStream = null;
private static FileOutputStream fileOutputStream = null;
private static FileChannel fileChannelOutput = null;
private static FileChannel fileChannelInput = null;
private static Thread copyDirThread;
private static BufferedInputStream inbuff = null;
private static BufferedOutputStream outbuff = null;
/**
* handler用于在主线程刷新ui
*/
private final static Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 0) {
int progress = msg.getData().getInt("progress");
long fileVolume = msg.getData().getLong("fileVolume");
progressDialog.setProgress(progress);
progressDialog.setProgressText(progress + "%");
progressDialog.setFileVolumeText(fileVolume * progress / 100 + " MB/" + fileVolume + " MB");
} else if (msg.what == 1) {
if (progressDialog != null) {
int fileVolume = msg.getData().getInt("fileVolume");
progressDialog.setFileVolumeText(0 + " MB/" + fileVolume + " MB");
}
} else if (msg.what == 3) {
Log.e("jinchen", "源文件不存在");
}
};
};
/**
* 复制单个文件
*/
public static boolean copyFile(final String oldPathName, final String newPathName, Context context) {
//大于50M时,才显示进度框
final File oldFile = new File(oldPathName);
if (oldFile.length() > 50 * 1024 * 1024) {
if (progressDialog == null) {
progressDialog = new CopyProgressDialog(context);
progressDialog.setOnCancelListener(new CopyProgressDialog.OnCancelListener() {//点击返回取消时,关闭线程和流
@Override
public void onCancel() {
run = null;
copyFileThread.interrupt();
copyFileThread = null;
try {
fileInputStream.close();
fileOutputStream.close();
fileChannelOutput.close();
fileChannelInput.close();
} catch (IOException e) {
Log.e("CopyPasteUtil", "CopyPasteUtil copyFile error:" + e.getMessage());
}
}
});
}
progressDialog.show();
progressDialog.setNameText(oldPathName);
}
run =