java - 如何让数组的大小自动增长和收缩?

标签 java

            int filename = 100;
    String[] fileName = new String[filename];
    int a = 0;
    int totalCount = 0;
    int wordCount = 0;

    // Count the number of documents containing the query

    System.out.println("Please enter the query  :");
    Scanner scan2 = new Scanner(System.in);
    String word2 = scan2.nextLine();
    String[] array2 = word2.split(" ");
    int[] numofDoc = new int[array2.length];

    for (int b = 0; b < array2.length; b++) {

        numofDoc[b] = 0;

        for (int i = 0; i < filename; i++) {

            try {

                BufferedReader bf = new BufferedReader(new FileReader(
                        "C:\\Users\\user\\fypworkspace\\FYP\\abc"
                                + i + ".txt"));

                int matchedWord = 0;

                Scanner s2 = new Scanner(bf);

                {

                    while (s2.hasNext()) {
                        if (s2.next().equals(array2[b]))
                            matchedWord++;
                    }

                }
                if (matchedWord > 0)
                    numofDoc[b]++;

            } catch (IOException e) {
                System.out.println();
            }

        }
        _resultArea.append(array2[b]
                + " --> This number of files that contain this term  "
                + numofDoc[b]+ newline);
    }

嗨,这是我的代码,用于计算包含用户键入的特定输入的文件数量。该代码分析文本文件的文件夹并搜索文本文件是否有输入。 我现在面临的问题是,我现在声明数组大小为100。这意味着无论文件夹是否有100个文件,它将处理100个文本文件。 如何让程序处理文件夹内确切数量的文本文件?

注意:文本文件的数量是动态的。它的文件夹内没有固定数量的文本文件。

最佳答案

看看java.io.File.list(),并使用List

例如:

File[] files = dir.list();
List<File> list = new LinkedList<File>();
for (File f : files) {
    if (/* f matches our criteria */) {
        list.add(f);
    }
}

如果您之后需要一个数组,请执行以下操作:

File[] array = list.toArray(new File[list.size()]);

关于java - 如何让数组的大小自动增长和收缩?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5489178/

相关文章:

java - 使用 Java 8 流形成特定列表

java - Azure - Java 应用程序

java - Java 中的隐式转换

java - 将 Spring tx 与任务混合

Java:如何监听php发送的http POST请求?

java - Java 中的错误处理 InputMismatchException

java - 如何在独立的 Java 代码中读取 Parquet 文件?

java - Hadoop FileSystem.getConf引发java.util.NoSuchElementException

java - anyMatch 是否像 filter + findFirst 那样具有确定性?

java - 如何拆分字符串以获得特定字符和不确定字符之间的句子