繁体   English   中英

如何在Jlist中检查文件是否存在

[英]How to check for file existence inside a Jlist

我通过JFileChooser在我的JList中添加了一些文件。 我使用下面的代码来添加我的内容:

                for (File file : fileChooser.getSelectedFiles()) {
                        vector.addElement(file);
                 }
                System.out.println("Added..!!");
                list.updateUI();

现在添加文件后,我想检查JList中是否存在abc.xml或123.txt或任何其他特定文件。 任何人都可以建议我如何检查JList中的特定文件?

我试过的是使用这种形式的迭代器;

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

但是,这并没有解决我的目的,因为它没有特别关注文件。 例如,如果我的输入是1.xml,2.xml和abx.xml,我得到的输出是,文件不存在,文件不存在,文件存在。

你们中的任何人都可以指导我完成这个......

File abc = new File("abc.xml");
boolean abcExists = vector.contains(abc);

如果要修复算法,请使用布尔变量:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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