在文本文件中搜索JAVA中的名称列表
我有以下资料:在文本文件中搜索JAVA中的名称列表,java,list,search,full-text-search,directory,Java,List,Search,Full Text Search,Directory,我有以下资料: 包含许多文件(约300000个)的文件夹,名为“AllFileFolder” 名称列表,命名为“名称列表” 名为“filteredFolder”的空文件夹 我想通过将包含列表中任何名称的任何文件移动到空文件夹“filteredFolder”来过滤文件夹“AllFilesFolder” 我已通过以下代码解决此问题: public static void doIt(List<String>namesList, String AllFilesFolder, String f
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);
}
}
}
publicstaticvoiddoit(ListnamesList,stringallfilesfolder,stringfilteredfolder)抛出FileNotFoundException{
//在这里,我们将所有文件放在列表变量名为“filesList”的原始文件夹中
File[]filesList=新文件(AllFilesFolder).listFiles();
//把文件一个接一个地看了一遍
对于(文件f:filesList){
试一试{
FileReader fr=新的FileReader(f);
BufferedReader读取器=新的BufferedReader(fr);
字符串行=”;
//此变量用于测试文件是否包含名称
//我们将其设置为false。
布尔值goodDoc=false;
//一行一行地检查文件以确定名称(如果有类似的问题,我会考虑)
而((line=reader.readLine())!=null){
用于(字符串名称:名称列表){
if(行包含(名称)){
goodoc=true;
}
}
}
reader.close();
//如果此文件包含名称,我们将此文件放入另一个文件夹“filteredFolder”
国际单项体育联合会(goodDoc){
InputStream InputStream=新文件InputStream(f);
OutputStream out=新文件OutputStream(新文件(filteredFolder+f.getName());
int read=0;
字节[]字节=新字节[4096];
而((read=inputStream.read(bytes))!=-1){
输出。写入(字节,0,读取);
}
inputStream.close();
out.flush();
out.close();
}
}捕获(例外e){
系统错误println(e);
}
}
}
通过这样做,我有两个问题需要你的建议来解决:
非常感谢您我将每个文件阅读两次,一次用于搜索,另一次用于将其放入另一个文件夹。 使用NIO可以提高拷贝性能。下面是一个例子,如果您可以使用Java7,那么您可以使用 在搜索名称列表时,我必须让循环逐个获取名称,是否有办法搜索列表一次(无循环)。
使用
HashSet
存储名称,并使用contains()
方法。这是一个O(1)操作。或者另一个建议是在设置goodDoc=true时使用代码>添加一个中断代码>。一旦你确定文件中有你的一个单词,这将阻止你一直读到文件的末尾。很好,谢谢@OldCurmudgeonThank you@Pangea。Files.copy()
确实节省了时间。但是,扫描仪功能
对我不起作用。我很感激。