编程语言您现在的位置是:首页 > 博客日志 > 编程语言

java实现遍历整个目录查找文件内容的功能

<a href='mailto:'>微wx笑</a>的头像微wx笑 2019-08-30编程语言1995 26 0关键字: java  

java实现遍历整个目录查找文件内容的功能,也就是查找哪些文件中包含指定的内容。

java实现遍历整个目录查找文件内容的功能HDW无知


HDW无知

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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package com.weixiao.sinablog;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
 
public class IOHelper {
 
    private static Logger logger = Logger.getLogger(IOHelper.class);
 
    /**
     * 获取 BufferedReader 实例
     * @author lipw
     * @date   2017年12月14日上午9:50:37
     * @param filePath 文件路径
     * @return
     */
    public static BufferedReader getBufferedReader(String filePath) {
        File file = new File(filePath);
        logger.warn(file.getAbsolutePath());
         
        BufferedReader reader = null;
        if (file.exists()){
            try {
                reader = new BufferedReader(new FileReader(file));
            catch (Exception e) {
                e.printStackTrace();
            finally {
                // todo
            }
        }
        return reader;
    }
 
    /**
     * 获取 BufferedWriter 实例
     * @author lipw
     * @date   2017年12月14日上午9:50:07
     * @param filePath 文件路径
     * @return
     */
    public static BufferedWriter getBufferedWriter(String filePath) {
        File file = new File(filePath);
        logger.warn(file.getAbsolutePath());
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(file));
        catch (Exception e) {
            e.printStackTrace();
        finally {
            // todo
        }
        return writer;
    }
 
    /**
     * 处理博客排序
     * @author lipw
     * @date   2017年12月14日上午9:47:06
     * @param filePath 混序文件路径
     * @param outPath 按顺序排列的输出文件路径
     */
    public static void handBlogOrder(String filePath, String outPath) {
        BufferedReader reader = getBufferedReader(filePath);
        BufferedWriter writer = getBufferedWriter(outPath);
 
        // 用户按排名记录
        Map<Integer, String> blogMap = new HashMap<Integer, String>();
 
        if (reader == null) {
            logger.warn("读取文件失败!");
            return;
        }
 
        if (writer == null) {
            logger.warn("写入文件失败!");
            return;
        }
 
        String lineStr = null;
        int line = 1;
        try {
            // 逐行读取并处理
            while ((lineStr = reader.readLine()) != null) {
                // 6,===http://blog.csdn.net/augusdi
                lineStr = lineStr.replaceAll("\\[com.weixiao.download.CsdnBlogDownloader\\]\\-排名:""");
                String[] blog = lineStr.split(",===");
                if (blog.length != 2) {
                    continue;
                }
 
                if (blog[0].length() > 3) {
                    continue;
                }
                Integer num = Integer.parseInt(blog[0]);
                if (num > 200) {
                    continue;
                }
                System.out.println("line" + line + ":" + lineStr);
                line++;
                // 放到 Map 缓存中
                blogMap.put(num, lineStr);
 
            }
 
            // 根据排名索引读取并写入文件
            for (int i = 0; i < 201; i++) {
                lineStr = blogMap.get(i);
                if (lineStr != null) {
                    writer.write(lineStr + "\r\n");
                }
            }
        catch (Exception e) {
            e.printStackTrace();
        finally {
            // 用完了记得关闭
            if (reader != null) {
                try {
                    reader.close();
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
            // 用完了记得关闭
            if (writer != null) {
                try {
                    writer.close();
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
     
    /**
     * 遍历指定目录及子目录下的文件
     
     * @author testcs_dn
     * @date  2014年12月12日下午2:33:49
     * @param file 要遍历的指定目录
     * @param collector 符合条件的结果添加到此List<File>中
     * @param pathInclude 路径中包含指定的字符串
     * @param fileNameInclude 文件名(不包含扩展名)中包含指定的字符串
     * @param extnEquals 文件扩展名为指定字符串
     * @throws IOException
     */
    public static void listFiles(File file,List<File> collector, String pathInclude, String fileNameInclude, String extnEquals, String searchContent) throws IOException {
        if (file.isFile() 
                && (StringUtils.isBlank(pathInclude) || file.getAbsolutePath().indexOf(pathInclude) != -1)
                && (StringUtils.isBlank(fileNameInclude) || file.getName().indexOf(fileNameInclude) != -1)
                && (StringUtils.isBlank(extnEquals) || file.getName().endsWith(extnEquals))
                ){
            if (contains(file.getAbsolutePath(), searchContent)){
                collector.add(file);
            }
        }
        if((!file.isHidden() && file.isDirectory()) && !isIgnoreFile(file)) {
            File[] subFiles = file.listFiles();
            for(int i = 0; i < subFiles.length; i++) {
                listFiles(subFiles[i],collector, pathInclude, fileNameInclude, extnEquals, searchContent);
            }
        }
    }
     
    private static boolean isIgnoreFile(File file) {
        List<String> ignoreList = new ArrayList<String>();
        ignoreList.add(".svn");
        ignoreList.add("CVS");
        ignoreList.add(".cvsignore");
        ignoreList.add("SCCS");
        ignoreList.add("vssver.scc");
        ignoreList.add(".DS_Store");
        for(int i = 0; i < ignoreList.size(); i++) {
            if(file.getName().equals(ignoreList.get(i))) {
                return true;
            }
        }
        return false;
    }
 
    /**
     * 判断文件中是否包含指定的内容
     * @author lipw
     * @date   2019年6月6日下午1:46:20
     * @param filePath
     * @param searchContent
     * @return
     */
    public static boolean contains(String filePath, String searchContent) {
        if (null == searchContent || searchContent.isEmpty() || searchContent.length() == 0){
            return false;
        }
        BufferedReader reader = getBufferedReader(filePath);
         
        if (reader == null) {
            logger.warn("读取文件失败!");
            return false;
        }
 
        String lineStr = null;
        try {
            // 逐行读取并处理
            while ((lineStr = reader.readLine()) != null) {
                if (lineStr.indexOf(searchContent) != -1){
                    return true;
                }
            }
        catch (Exception e) {
            e.printStackTrace();
        finally {
            // 用完了记得关闭
            if (reader != null) {
                try {
                    reader.close();
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
     
     
    public static void main(String[] args) {
        //处理博客排序
        //handBlogOrder("/Users/aven/Downloads/blogOrder.txt", "/Users/aven/Downloads/blogOrder200.txt");
        ///Users/aven/Downloads/EmpireCMS_7.5_SC_UTF8/upload
         
        List<File> collector = new ArrayList<File>();
        try {
            //listFiles(new File("/Users/aven/Downloads/EmpireCMS_7.5_SC_UTF8/upload/e/"), collector, null, null, null, "[!--bclassname--]");
            //listFiles(new File("/Users/aven/Downloads/EmpireCMS_7.5_SC_UTF8/upload/e/"), collector, null, null, null, "listshowclass"); // /Users/aven/Downloads/EmpireCMS_7.5_SC_UTF8/upload/e/admin/template/MakeBq.php
            //listFiles(new File("/Users/aven/Downloads/EmpireCMS_7.5_SC_UTF8/upload/e/"), collector, null, null, null, "function AddNews("); 
            //listFiles(new File("/Users/aven/Downloads/EmpireCMS_7.5_SC_UTF8/upload/e/"), collector, null, null, null, "function GetFpicToTpic(");
            //listFiles(new File("/Users/aven/Downloads/EmpireCMS_7.5_SC_UTF8/upload/e/"), collector, null, null, null, "function ReturnAddF");
            //listFiles(new File("/Users/aven/Downloads/EmpireCMS_7.5_SC_UTF8/upload/e/"), collector, null, null, null, "function EditNews");
            //listFiles(new File("/Users/aven/Downloads/ivu4e.com20190815/"), collector, null, null, null, "function printerror");
            listFiles(new File("/Users/aven/Downloads/EmpireCMS_7.5_SC_UTF8/upload/e/"), collector, nullnullnull"function do_dbconnect");
             
            System.out.println("---------");
            System.out.println("---------");
            System.out.println("---------");
            System.out.println("---------");
            for (File file : collector){
                System.out.println(file.getAbsolutePath());
            }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


HDW无知

本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/blog/lang/2019-08-30/172.html

很赞哦! (30) 有话说 (0)

文章评论