直接上代码:
复制代码
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102/** * 目标:复制src下文件到srcBak文件夹下 * 思路: * 1.找出src下所有文件,把绝对路径与文件名放到一个元素类型为String的List中 * 2.将src替换为srcBak,得到目标文件的绝对路径和文件名 * 3.进行复制 * @author yajun * */ public class FileCopy { private List<String> listFiles(String dir_str){ //局部变量 List<String> files_str=new ArrayList<String>(); List<File> files_file=new ArrayList<File>(); File dir_file=new File(dir_str); String file_str; //获取文件列表 files_file=Arrays.asList(dir_file.listFiles()); //遍历文件列表,获取带绝对路径的文件名 for(File file:files_file){ //判断:如果是文件,则添加,如果是目录,则递归 if(file.isFile()){ file_str=file.getAbsolutePath(); files_str.add(file_str); } else{ //传参和返回值是个重点!!!! files_str=listFiles(dir_str+"\"+file.getName()); } } return files_str; } @Test public void testListFiles(){ System.out.println(listFiles("src")); } private void copyDir(String srcDir_str){ /** * 1.获取dir中文件名List * 2.根据文件吗构造目标文件名,放入List */ //局部变量 List<String> srcFile_str=new ArrayList<String>(); List<String> destFile_str=new ArrayList<String>(); //1.获取dir中的文件名List srcFile_str=listFiles(srcDir_str); //2.根据文件吗构造目标文件名,放入List for(String str:srcFile_str){ destFile_str.add(str.replace(srcDir_str, srcDir_str+"Bak")); } //调试信息 System.out.println("目标文件列表:"+destFile_str); //3.复制 for(int i=0;i<srcFile_str.size();i++){ copy(srcFile_str.get(i),destFile_str.get(i)); } } @Test public void testCopyDir(){ copyDir("src"); } private void copy(String src_str,String dest_str){ //局部变量 File srcFile=new File(src_str); String destDir_str=dest_str.substring(0,dest_str.lastIndexOf("\")); File destDir=new File(destDir_str); FileInputStream fis=null; FileOutputStream fos=null; byte temp[]=new byte[1024]; // if(!srcFile.exists()){ System.out.println("源文件不存在"); return; } if(!destDir.exists()){ destDir.mkdirs(); } try { fis=new FileInputStream(srcFile); fos=new FileOutputStream(dest_str); int len=0; while((len=fis.read(temp))!=-1){ fos.write(temp,0,len); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ try { fis.close(); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }//End of try-catch } @Test public void testCopy(){ copy("D:\test\down.txt","D:\test\copy.txt"); } }
最后
以上就是诚心冥王星最近收集整理的关于IO流之复制文件夹中及其子目录中的文件的全部内容,更多相关IO流之复制文件夹中及其子目录中内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复