【发布时间】:2020-02-22 22:35:21
【问题描述】:
我正在尝试从两个不同的文件中读取数据,一个是 csv 格式,另一个文件来自 xml 数据。使用 completeFuture 我正在尝试从两个文件中异步读取数据。我收到类型转换错误。 请让我知道我是否在下面的代码中遵循正确的方法来使用 completefuture 对象
例外:
java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class java.util.function.Supplier (java.util.ArrayList and java.util.function.Supplier are in module java.base of loader 'bootstrap')
从主线程读取数据的代码
CompletableFuture<Object> csvdata = CompletableFuture.supplyAsync((Supplier<Object>) processdatacsv());
CompletableFuture<Object> xmldata1 = CompletableFuture.supplyAsync((Supplier<Object>) processxmldata());
List<String[]> csvfiledata = null;
if (csvdata.isDone())
csvfiledata = (List<String[]>) csvdata.get();
List<String[]> xmlfiledata = null;
if (xmldata1.isDone())
xmlfiledata = (List<String[]>) xmldata1.get();
private List<String[]> processdatacsv() {
CSVReader reader = null;
Resource resource1 = new ClassPathResource("sample.csv");
try {
String csvFile = resource1.getFile().toString();
reader = new CSVReader(new FileReader(csvFile));
return reader.readAll();
} catch (Exception e) {
LOGGER.error("Error while process csv records");
return null;
}
}
private List<String[]> processxmldata() {
Resource resource = new ClassPathResource("sample.xml");
File file;
try {
file = resource.getFile();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("record");
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
List<String[]> dataList = new ArrayList<String[]>();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) node;
String[] data = new String[3];
data[0] = eElement.getAttribute("reference").toString();
data[1] = eElement.getElementsByTagName("Number").item(0).getTextContent().toString();
data[2] = eElement.getElementsByTagName("des").item(0).getTextContent().toString();
}
}
return dataList;
} catch (Exception e) {
LOGGER.error("Error while process csv records");
return null;
}
}
【问题讨论】: