拷贝文件或文件夹
1456
7public void copyFile(String source, String target) {
8 // 源文件
9 File sourceFile = new File(source);
10 if (!sourceFile.exists()) {
11 return;
12 }
13
14 // 目标文件
15 File targetFile = new File(target);
16
17 // 文件拷贝
18 if (sourceFile.isFile()) {
19 copyFromChanel(sourceFile, targetFile);
20 return;
21 }
22
23 // 文件夹拷贝
24 if (!targetFile.exists()) {
25 targetFile.mkdirs();
26 }
27 for (File file: sourceFile.listFiles()) {
28 copyFile(file.getAbsolutePath(), target + File.separator + file.getName());
29 }
30
31}
利用文件管道拷贝文件
1456
7public void copyFromChanel(File source, File target) {
8
9 // 文件流
10 FileInputStream fis = null;
11 FileOutputStream fos = null;
12
13 // 文件管道
14 FileChannel fci = null;
15 FileChannel fco = null;
16 try {
17
18 // 文件流
19 fis = new FileInputStream(source);
20 fos = new FileOutputStream(target);
21
22 // 文件管道
23 fci = fis.getChannel();
24 fco = fos.getChannel();
25
26 // 连接两个通道,并且从fci通道读取,然后写入fco通道
27 fci.transferTo(0, fci.size(), fco);
28
29 } catch (IOException e) {
30 e.printStackTrace();
31 } finally {
32 try {
33 if (fis != null) fis.close();
34 if (fci != null) fci.close();
35 if (fos != null) fos.close();
36 if (fco != null) fco.close();
37 } catch (IOException e) {
38 e.printStackTrace();
39 }
40 }
41}