我有以下内容:
- 包含许多文件(大约 300000 个)的文件夹,名为“AllFilesFolder”
- 名称列表,名为“namesList”
- 一个名为“filteredFolder”的空文件夹
我想通过将包含列表中任何名称的任何文件移动到空文件夹“filteredFolder”来过滤文件夹“AllFilesFolder”。
我通过以下代码解决了这个问题:
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 循环来逐个获取名称,有没有办法一次搜索列表(没有循环)。
提前谢谢了