2011-03-30 121 views
0
  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个文件。 如何让程序处理文件夹内的文本文件的确切数量?如何让数组的大小自动增长和缩小?

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

回答

0

要么跟踪您读取的文本文件的数量,要么使用具有size属性的List

2

Java数组具有静态大小。您应该使用List(最经常使用的实现是ArrayList),它可以动态安全地增长和缩小。更不用说(自Java 5以来)它是通用的,即类型安全。

0

您是否尝试过使用列表像

List<String> fileName = new ArrayList<String>(); 

,或者你可以只维护文件的数量,你有

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

我不是专家,但我敢肯定,你可以使用arraylist

3

查看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()]);