[英]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.