简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM