我有以下代码:
ArrayList<String> File_name = new ArrayList<String>();
try {
//Reading an XML file, created above
File fXmlFile = new File("C:\\Users\\V\\Documents\\diplwmatiki\\temp\\dokimi.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
//Printing the attributes of the XML file
System.out.println("\nRoot element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("element");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("element : " + eElement.getAttribute("id"));
System.out.println("File_name : " + eElement.getElementsByTagName("name").item(0).getTextContent());
File_name.add(eElement.getElementsByTagName("name").item(0).getTextContent());
}
}
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("\n");
System.out.println(File_name);
System.out.println("\n");
//Creating an list having all files of a directory
String path = "C:\\Users\\V\\Documents\\diplwmatiki\\SFBs";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}
我想比较两者ArrayLists
使用 files.retainAll(File_name);
创建,因为我需要保留第二个列表中的文件,其名称作为字符串存在于第一个列表中。 RetainAll();
不起作用,因为这是两种不同的类型: String
和File
。我正在尝试制作如下所示的过滤器,但出现语法错误,当我尝试更正它们时,这些错误似乎不起作用。这是过滤器:
String[] myFiles = folder.list(new FilenameFilter(){
for (int i=0; i < listOfFiles.length; i++){
public boolean accept;File folder; String fileName;{
return fileName.startsWith(File_name[i]);
System.out.println(folder);
}
});
我在第一行和最后一行插入或删除标记时出现错误。我不使用retainAll()
在这个过滤器中。
很抱歉这篇文章很长,谢谢!
最佳答案
您至少可以通过两种方式做到这一点,使用 File.getName()
- 只需迭代您的列表,并将您的
String
名称与对第二个列表中的File
元素调用getName()
进行比较即可。< - 或者根据您的文件名创建另一个列表,生成另一个
String
列表,然后然后使用retainAll()
关于java - 如何在 Java 中比较 arraylist<string> 与 arraylist<file>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19293751/