【发布时间】:2012-08-02 12:39:12
【问题描述】:
我有以下:
- 包含许多文件(大约 300000 个)的文件夹,名为“AllFilesFolder”
- 名称列表,名为“namesList”
- 一个名为“filteredFolder”的空文件夹
我想过滤文件夹“AllFilesFolder”,方法是将列表中包含任何名称的任何文件移动到空文件夹“filteredFolder”。
我通过以下代码解决了这个问题:
public static void doIt(List<String>namesList, String AllFilesFolder, String filteredFolder) throws FileNotFoundException {
// here we put all the files in the original folder in List variable name "filesList"
File[] filesList = new File(AllFilesFolder).listFiles();
// went throught the files one by one
for (File f : filesList) {
try {
FileReader fr = new FileReader(f);
BufferedReader reader = new BufferedReader(fr);
String line = "";
//this varibale used to test withir the files contins names or not
//we set it to false.
boolean goodDoc = false;
//go through the file line by line to chick the names (I wounder if there are a simbler whay)
while ((line = reader.readLine()) != null) {
for(String name:namesList){
if ( line.contains(name)) {
goodDoc = true;
}
}
}
reader.close();
// if this file contains the name we put this file into the other folder "filteredFolder"
if (goodDoc) {
InputStream inputStream = new FileInputStream(f);
OutputStream out = new FileOutputStream(new File(filteredFolder + f.getName()));
int read = 0;
byte[] bytes = new byte[4096];
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
}
} catch (Exception e) {
System.err.println(e);
}
}
}
通过这样做,我有两个问题需要您的建议来解决:
我将每个文件读取两次,一次用于搜索,另一次将其放入另一个文件夹。
在搜索 namesList 时,我有 for 循环一个一个地获取名称,有没有办法一次搜索列表(不循环)。
在此先感谢
【问题讨论】:
-
当您设置
goodDoc = true;时添加break;。一旦您确定文件中包含您的单词之一,这将阻止您阅读到文件末尾。 -
好点谢谢@OldCurmudgeon
标签: java list search full-text-search directory