我通过 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 变量:
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");
}
关于java - 如何检查 Jlist 中的文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10412086/