Reputation: 293
I have a few files added in my JList via the JFileChooser. I use the below piece of code to add my contents:
for (File file : fileChooser.getSelectedFiles()) {
vector.addElement(file);
}
System.out.println("Added..!!");
list.updateUI();
Now after adding the files, I would like to check if abc.xml or 123.txt or any other specific file is present in the JList or not. Can anybody suggest me how do I check for particular files inside the JList?
What I have tried is to use an Iterator in this form;
Iterator<File> it = vector.iterator();
while(it.hasNext())
if(it.next().getName().equals("abc.xml"))
System.out.println("Yes..abc.xml exists");
else
System.out.println("OOPS! abc.xml does not exist");
But, this does not solve my purpose since it does not take the file in particular. For example, if my input is 1.xml, 2.xml and abx.xml, the output i am getting is, file does not exist, file does not exist and file exists.
Can any of you please guide me through this...
Upvotes: 1
Views: 209
Reputation: 691765
File abc = new File("abc.xml");
boolean abcExists = vector.contains(abc);
If you want to fix your algorithm, then use a boolean variable:
boolean exists = false;
for (File f : vector) {
if (f.getName().equals("abc.xml")) {
exists = true;
break; // no need to continue the loop
}
}
if (exists) {
System.out.println("Yes..abc.xml exists");
else {
System.out.println("OOPS! abc.xml does not exist");
}
Upvotes: 3