gpt4 book ai didi

java - 如何在 Java 中比较 arraylist 与 arraylist

转载 作者:行者123 更新时间:2023-12-02 06:39:23 25 4
gpt4 key购买 nike

我有以下代码:

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();不起作用,因为这是两种不同的类型: StringFile 。我正在尝试制作如下所示的过滤器,但出现语法错误,当我尝试更正它们时,这些错误似乎不起作用。这是过滤器:

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()

  1. 只需迭代您的列表,并将您的 String 名称与对第二个列表中的 File 元素调用 getName() 进行比较即可。<
  2. 或者根据您的文件名创建另一个列表,生成另一个String列表,然后然后使用retainAll()

关于java - 如何在 Java 中比较 arraylist<string> 与 arraylist<file>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19293751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com