gpt4 book ai didi

xml - Java XML 文件比较

转载 作者:行者123 更新时间:2023-11-30 04:30:52 29 4
gpt4 key购买 nike

我正在尝试使用 XMLUnit 比较 2 个 XML 文件。我在eclipse中尝试使用以下代码,我已将要比较的xml文件放在本地目录中。

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.xml.sax.SAXException;

public class ComparisonTest {

public static void main(String[] args) {
URL url1 = ComparisonTest.class.getResource("D:/reference.xml");
URL url2 = ComparisonTest.class.getResource("D:/comparison.xml");
FileReader fr1 = null;
FileReader fr2 = null;
try {
fr1 = new FileReader(url1.getPath());
fr2 = new FileReader(url2.getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}

try {
Diff diff = new Diff(fr1, fr2);
System.out.println("Similar? " + diff.similar());
System.out.println("Identical? " + diff.identical());

DetailedDiff detDiff = new DetailedDiff(diff);
List differences = detDiff.getAllDifferences();
for (Object object : differences) {
Difference difference = (Difference)object;
System.out.println("***********************");
System.out.println(difference);
System.out.println("***********************");
}

} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

我收到错误

Exception in thread "main" java.lang.NullPointerException
at com.org.comparison.ComparisonTest.main(ComparisonTest.java:21)

我不明白为什么?

最佳答案

我不确定您是否可以将“D:/reference.xml”作为资源传递。只需将路径传递给 FileReader 的构造函数即可:

FileReader fr1 = null;
FileReader fr2 = null;
try {
fr1 = new FileReader("D:/reference.xml");
fr2 = new FileReader("D:/comparison.xml");
} catch (FileNotFoundException e) {
e.printStackTrace();
}

我很确定 getResource 会给你 null。

URL url1 = ComparisonTest.class.getResource("D:/reference.xml");
URL url2 = ComparisonTest.class.getResource("D:/comparison.xml");
System.out.println(url1 + " " + url2); // I suppose output is "null null"

关于xml - Java XML 文件比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14686292/

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