【问题标题】:Search a text file for List of names in JAVA在文本文件中搜索 JAVA 中的名称列表
【发布时间】:2012-08-02 12:39:12
【问题描述】:

我有以下:

  1. 包含许多文件(大约 300000 个)的文件夹,名为“AllFilesFolder”
  2. 名称列表,名为“namesList”
  3. 一个名为“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);
        }
    }
}

通过这样做,我有两个问题需要您的建议来解决:

  1. 我将每个文件读取两次,一次用于搜索,另一次将其放入另一个文件夹。

  2. 在搜索 namesList 时,我有 for 循环一个一个地获取名称,有没有办法一次搜索列表(不循环)。

在此先感谢

【问题讨论】:

  • 当您设置goodDoc = true; 时添加break;。一旦您确定文件中包含您的单词之一,这将阻止您阅读到文件末尾。
  • 好点谢谢@OldCurmudgeon

标签: java list search full-text-search directory


【解决方案1】:

我将每个文件读取两次,一次用于搜索,另一次将其放入另一个文件夹。

使用 NIO 可以提高复制性能。这是code example. 如果你可以使用Java 7 那么你可以使用Files.copy()

在搜索 namesList 时,我有 for 循环来逐个获取名称,有没有办法一次搜索列表(不循环)。

使用HashSet 存储名称并使用contains() 方法。这是一个 O(1) 操作。或者另一个建议是使用Scanner.findWithinHorizon(pattern, horizon)

【讨论】:

  • 谢谢@Pangea。 Files.copy() 确实节省了时间。但是,Scanner function 没有与我合作。我很感激。
猜你喜欢
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 1970-01-01
  • 1970-01-01
  • 2018-07-25
  • 1970-01-01
相关资源
最近更新 更多