P2-11 案例:拷贝文件夹

案例:拷贝文件夹


需求说明

  • 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++)//用到序号,for循环好找
{
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("搞定");


P2-11 案例:拷贝文件夹
http://example.com/2024/08/06/SE101-零基础玩Java/Part2-笔记/P2-11 案例:拷贝文件夹/
Author
John Doe
Posted on
August 6, 2024
Licensed under