首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java实现文件夹(包括其中的子文件夹、子文件)的复制——递归

java实现文件夹(包括其中的子文件夹、子文件)的复制——递归

作者头像
用户1737026
发布2018-05-17 17:24:16
2.3K0
发布2018-05-17 17:24:16
举报
文章被收录于专栏:五毛程序员五毛程序员

这是学校java课的一道实验题,题目如下:编程,根据指定的源和目标位置,完成指定文件或文件夹(包括其中的子文件夹、子文件)的复制。

以下是我的实现,使用了递归:

 1 package com.simon.myfinal;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.InputStream;
 7 
 8 /**
 9  * Created by Rainmer on 2015/6/28.
10  */
11 public class FileCopy {
12     public static void main(String[] args) {
13         String oldPath = "D:/bower";
14         String newPath = "D:/bowerCopy";
15         File dirNew = new File(newPath);
16         dirNew.mkdirs();//可以在不存在的目录中创建文件夹
17         directory(oldPath, newPath);
18         System.out.println("复制文件夹成功");
19     }
20 
21     /**
22      * 复制单个文件
23      * @param oldPath 要复制的文件名
24      * @param newPath 目标文件名
25      */
26     public static void copyfile(String oldPath, String newPath) {
27         int hasRead = 0;
28         File oldFile = new File(oldPath);
29         if (oldFile.exists()) {
30             try {
31                 FileInputStream fis = new FileInputStream(oldFile);//读入原文件
32                 FileOutputStream fos = new FileOutputStream(newPath);
33                 byte[] buffer = new byte[1024];
34                 while ((hasRead = fis.read(buffer)) != -1) {//当文件没有读到结尾
35                     fos.write(buffer, 0, hasRead);//写文件
36                 }
37                 fis.close();
38             } catch (Exception e) {
39                 System.out.println("复制单个文件操作出错!");
40                 e.printStackTrace();
41             }
42         }
43     }
44 
45     /**
46      *
47      * @param oldPath 要复制的文件夹路径
48      * @param newPath 目标文件夹路径
49      */
50     public static void directory(String oldPath, String newPath) {
51         File f1 = new File(oldPath);
52         File[] files = f1.listFiles();//listFiles能够获取当前文件夹下的所有文件和文件夹
53         for (int i = 0; i < files.length; i++) {
54             if (files[i].isDirectory()) {
55                 File dirNew = new File(newPath + File.separator + files[i].getName());
56                 dirNew.mkdir();//在目标文件夹中创建文件夹
57                 //递归
58                 directory(oldPath + File.separator + files[i].getName(), newPath + File.separator + files[i].getName());
59             } else {
60                 String filePath = newPath + File.separator + files[i].getName();
61                 copyfile(files[i].getAbsolutePath(), filePath);
62             }
63 
64         }
65     }
66 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-06-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档