文件夹里边所有的文件的内容输出到一个txt文件

 1 package comparatorTest;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.OutputStream;
 8 import java.util.ArrayList;
 9 import java.util.List;
10 
11 public class Person {
12 
13     public static List<File> getFiles(String path) {
14         File root = new File(path);
15         List<File> files = new ArrayList<File>();
16         if (!root.isDirectory()) {
17             files.add(root);
18         } else {
19             File[] subFiles = root.listFiles();
20             for (File f : subFiles) {
21                 files.addAll(getFiles(f.getAbsolutePath()));
22             }
23         }
24         return files;
25     }
26 
27     public static void main(String[] args) throws IOException {
28         List<File> files = getFiles("F:\\1");
29         //写入文件,覆盖
30         File file = new File("F:\\被写入的文件.txt");
31         OutputStream out = new FileOutputStream(file);
32         StringBuffer sb = new StringBuffer();
33         for (File f : files) {
34             sb.append("\r\n");
35             String name = f.getName();
36             sb.append("文件名:" + name);
37             sb.append("\r\n");
38             /**
39              * 注意,本代码只复制html css js java, xml文件的内容,如有需要请自行修改
40              */
41             if (f.isFile() && name.endsWith(".html") || name.endsWith(".css") || name.endsWith(".js") || name.endsWith(".java") || name.endsWith(".xml")) {
42                 // 以字节流方法读取文件
43                 FileInputStream fis = null;
44                 try {
45                     fis = new FileInputStream(f);
46                     // 设置一个,每次 装载信息的容器
47                     byte[] buf = new byte[1024];
48                     // 开始读取数据
49                     int len = 0;// 每次读取到的数据的长度
50                     while ((len = fis.read(buf)) != -1) {// len值为-1时,表示没有数据了
51                         // append方法往sb对象里面添加数据
52                         sb.append(new String(buf, 0, len, "utf-8"));
53                     }
54                 } catch (IOException e) {
55                     e.printStackTrace();
56                 }
57             } else {
58                 System.out.println("文件不存在!");
59             }
60 
61         }
62         byte b[] = sb.toString().getBytes();
63         out.write(b);
64         out.close();
65     }
66 
67 }

猜你喜欢

转载自www.cnblogs.com/llawliet0001/p/10214630.html