案例:拷贝文件夹
需求说明
- 1、让用户分别选择源文件夹和目标文件夹,然后把源文件夹所有文件都拷贝到目标文件夹
- 2、考虑文件可能会很多,所以要显示拷贝进度
思路
1.弹出选择源文件夹
2.弹出选择目标文件夹
3.把源文件夹所有文件拷贝到目标文件夹
4.要显示拷贝进度(因为文件有可能会很多)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| String srcdir = GUI.dirOpenBox("请选择源文件夹"); String destdir = GUI.dirSaveBox("请选择目标文件夹"); File srcFile =new File(srcdir); File[] files = srcFile.listFiles(); for (int i =0;i< files.length;i++) { File file = files[i]; if (file.isDirectory()) { continue; } GUI.showProgressDialog("正在拷贝"+file.getName(),i,files.length); String destFilename = destdir+"/"+file.getName(); byte[] bytes = IOHelpers.readAllBytes(file); IOHelpers.writeAllBytes(destFilename,bytes); } GUI.closeProgressDialog(); GUI.msgBox("搞定");
|
分析
- 最佳写法肯定选择for循环,因为要有进度条,用序号去搞进度条
- 后面也有for增强的写法,但工作中很少看到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| String srcdir = GUI.dirOpenBox("请选择源文件夹"); String destdir = GUI.dirSaveBox("请选择目标文件夹"); int i= 0; File srcFile =new File(srcdir); File[] files = srcFile.listFiles(); for (File file :srcFile.listFiles()) { if (file.isDirectory()) { continue; } GUI.showProgressDialog("正在拷贝"+file.getName(),i,files.length); String destFilename = destdir+"/"+file.getName(); byte[] bytes = IOHelpers.readAllBytes(file); IOHelpers.writeAllBytes(destFilename,bytes); i++; } GUI.closeProgressDialog(); GUI.msgBox("搞定");
|