how to let the size of array to grow and shrink automatically?
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);
}
hi, this is my code for calculating number of files that contain a specific input keyed in by the user. This code analyze a folder of text files and search the text files whether it has the input or not. The problem i facing now is, i now declaring the array size of 100. It means that it will process 100 text files whether the folder have 100 files or not. How 开发者_如何学JAVAdo i let the program to process exact number of text files inside a folder ?
Note : The number of text files is dynamic. It doesnt has a constant number of text files inside the folder.
Take a look at java.io.File.list()
, and use a List
.
For example:
File[] files = dir.list();
List<File> list = new LinkedList<File>();
for (File f : files) {
if (/* f matches our criteria */) {
list.add(f);
}
}
If you need an array after that, do this:
File[] array = list.toArray(new File[list.size()]);
Java arrays are of static size. You should use a List
(whose most frequently used implementation is ArrayList
) instead, which can grow and shrink dynamically and safely. Not to mention that (since Java 5) it is generic, i.e. typesafe.
Either keep track of the number of text files you read, or use a List
, which has a size property.
I am no expert, but I am pretty sure you could use arraylist
Have you tried using a List like
List<String> fileName = new ArrayList<String>();
or you could just maintain the count of files you have
for (int i = 0; i < filenameCount; i++) {
精彩评论