复制多级文件夹
步骤
- 创建数据源File对象,路径是E:itcast
- 创建目的地File对象,路径是F:
- 写方法实现文件夹的复制,参数为数据源File对象和目的地File对象
- 判断数据源File是否是文件
a. 是文件:直接复制,用字节流
b. 不是文件:
在目的地下创建该目录
遍历获取该目录下的所有文件的File数组,
得到每一个File对象
回到3继续(递归)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57import java.io.*; public class demo{ public static void main(String[] args) throws IOException { //创建数据源目录File对象 File srcFile = new File("//Users//mac//Desktop//123"); //创建目的地目录File对象 File destFile = new File("//Users//mac//IdeaProjects//demo"); //复制目录文件 copyFolder(srcFile,destFile); } private static void copyFolder(File srcFile, File destFile) throws IOException { //判断是否为目录 if (srcFile.isDirectory()){ //是目录,创建与原目录名称一样的目录,遍历 //获取原目录名称 String srcFileName = srcFile.getName(); //创建目录 File newFolder = new File(destFile,srcFileName); //判断目录是否存在,不存在,则创建 if(!newFolder.exists()){ newFolder.mkdir(); } //遍历获取该目录下所有文件的File数组 File[] fileArray = srcFile.listFiles(); for(File file : fileArray){ copyFolder(file,newFolder); } }else{//不是目录,是文件,直接用字节流复制文件 File newFile = new File(destFile,srcFile.getName()); copyFile(srcFile,newFile); } } private static void copyFile(File srcFile, File destFile) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] bys = new byte[1024]; int len; while((len = bis.read(bys)) != -1){ bos.write(bys,0,len); } bos.close(); bis.close(); } }
最后
以上就是专一手套最近收集整理的关于IO流练习:复制多级文件夹(JAVA)的全部内容,更多相关IO流练习内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复