我有一个Swing应用,需要以CSV格式读取和写入文件。我在src/main/resources/dictData.dat
目前,当我通过
执行可执行jar时java -jar dictionary-jar-with-dependencies.jar
并尝试执行保存操作,我得到了
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.test.dictionary.utils.FileIO.writeToDataFile(FileIO.java:91)
at com.test.dictionary.dao.DictionaryDAO.writeToFile(DictionaryDAO.java:145)**
在这里,我有一个方法可以使用Apache CSV库将Map
结构的内容转换为CSV文件。
stacktrace上最顶层的消息是dataWriter.flush()
块中的finally {}
方法。
@Override
public void writeToDataFile(Map<String, Word> dictMap){
try {
Path path = Paths.get(dataUrl.toURI());
dataWriter = new FileWriter(path.toFile());
csvFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");
csvPrinter = new CSVPrinter(dataWriter, csvFormat);
csvPrinter.printRecord(CSVHeaderMapping.FILE_HEADER);
List<String> wordData;
//CSVPrinter.printRecord is best utilized with an Iterable object, thus the initialization of a new ArrayList
//for each dictionary value
for (Word word : dictMap.values()){
wordData = new ArrayList<>();
wordData.add(String.valueOf(word.getId()));
wordData.add(word.getWordName());
wordData.add(word.getWordDefinition());
wordData.add(word.getDateCreated().toString());
wordData.add(word.getDateLastUpdated().toString());
csvPrinter.printRecord(wordData);
}
} catch (NullPointerException | IOException | URISyntaxException e){
e.printStackTrace();
} finally {
try {
dataWriter.flush(); //throws a NPE here, stacktrace above
dataWriter.close();
csvPrinter.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
奇怪的是,从同一位置读取文件时遇到了类似的问题。通过
将文件打开转换为流来解决问题//Open file connection and read stream
dataUrl = classLoader.getResource(dictionaryFile);
dataReader = new InputStreamReader(dataUrl.openStream());
请注意,这仅在通过java -jar
执行时发生,并且此应用程序在IDE内部运行时可以正常工作。
答案 0 :(得分:1)
src
就不存在了。您永远不应该在源代码中引用它。考虑写入公共位置,而不是写入资源,可以存储在user.home
位置