How to check for file existence inside a Jlist

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...

Answers


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");
}

Need Your Help

ASP.NET AJAX Textbox to DataList/Grid

asp.net ajax asp.net-ajax datagridview

I'm looking to create a free-type textbox which onkeyout "filters" a datagrid below. The old way to do this was to write a webservice and call it on each press returning the results - I was hoping...