我通过一种方法传递CSVPrinter打印机,并且在内部循环中传递了printRecord方法。下面是该方法的代码段。
private void printToCsv(String currentDate, LinkedHashMap<String, LinkedList<CMonthlyStats>> contracts, CSVPrinter printer){
List<String> activeContracts = ContractMonthlyStatsReader.getListOfActiveContracts(currentDate, contrs);
for (String activeContract: activeContracts){
CMonthlyStatsR report = getCMonthlyStatsR(currentDate, activeContr, contracts.get(activeContr));
try {
printer.printRecord(
report.getAID(),
report.getMD(),
report.getAL(), report.getEL(),
ReportUtil.getMatchValue(),
report.getAFL(), report.getEFL(),
ReportUtil.getMatchValue(),
report.getAPF(), report.getEPF(),
ReportUtil.getMatchValue()
);
printer.flush();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
正在通过main方法中的另一种方法通过以下方式初始化打印机:
public void Main(){
.....
CSVFormat format = getformatWithHeaders();
final CSVPrinter printer = getCSVPrinter(format);
.....
for(String string: Strings){
.......
printToCsv(currentDate, contrs, printer);
.......
}
}
getCSVPrinter(format)方法的代码段:
private CSVPrinter getCSVPrinter(CSVFormat format){
try (final FileWriter newWriter = new FileWriter(System.getProperty("output.file"))){
try(final CSVPrinter printer = new CSVPrinter(newWriter, format)){
return printer;
}
}
catch (IOException e){
e.printStackTrace();
}
return null;
}
标头将打印到输出文件,但是每次尝试打印记录时,我都会得到
java.io.IOException: Stream closed
。处理IO一直是我的噩梦。请帮忙!CSVPrinter来自
org.apache.commons.csv
最佳答案
您遇到的错误是对Try-with-resources-statement
的错误解释。
在您的try块中,您先打开FileWriter
,然后打开CSVPrinter
:
try (final FileWriter newWriter = new FileWriter(System.getProperty("output.file"))){
try(final CSVPrinter printer = new CSVPrinter(newWriter, format)){
return printer;
}
}
catch (IOException e){
e.printStackTrace();
}
但是当您退回打印机时,它已经关闭,因为try-with-resources语句已关闭。
因此,如果您想退回打印机,请不要尝试使用资源
请查看此问题以获取更多信息:https://stackoverflow.com/a/22947904/5515060