【问题标题】:Wild Card Searching a file system folder in Java [duplicate]通配符在Java中搜索文件系统文件夹[重复]
【发布时间】:2014-10-26 18:14:22
【问题描述】:

我目前有一个 Java 程序,它在我的 windows 机器上的一个目录中循环数百个文件,在每个文件中搜索一个字符串。

我这样做是从 200 多个文件名中创建一个数组,并且程序执行没有问题。

我想知道是否有可能

A.使用通配符,因此每次更改要搜索的文件时,我都不必在代码中将 200 多个文件列为数组。

B 只搜索特定文件夹中的所有文件。

下面是我的代码,其中 inputFile 是文件数组。

 try {
            br = new BufferedReader(new FileReader(inputFile[i]));
            try {
                while((line = br.readLine()) != null)
                {
                    countLine++;
                    //System.out.println(line);
                    String[] words = line.split(" ");

                    for (String word : words) {
                        if (word.equals(inputSearch)) {
                            count++;
                            countBuffer++;
                        }
                    }

                    if(countBuffer > 0)
                    {
                        countBuffer = 0;
                        lineNumber += countLine + ",";
                    }

                }
                br.close();

【问题讨论】:

标签: java filesystems


【解决方案1】:

有一个方法listFiles() 列出了给定目录中的所有Files。

File directory = new File(-Path to directory-);
File[] files = directory.listFiles();

然后你可以迭代那个。但请注意,listFiles() 还会在读取文件之前获取您需要检查的所有子文件夹。

【讨论】:

  • 那行得通。谢谢....我可能遗漏了一些明显的东西,但我怎么知道该方法对文件使用的顺序?我无法确定它是如何对文件进行排序的。
  • 根据DocThere is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.
【解决方案2】:

【讨论】:

    猜你喜欢
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    相关资源
    最近更新 更多