我有一个 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)**
在这里,我有一个方法可以写入 Map
的内容。使用 Apache CSV 库将结构转换为 CSV 文件。
堆栈跟踪中最上面的消息位于 dataWriter.flush()
finally {}
中的方法 block 。
@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 中运行时可以完美运行。
最佳答案
-
程序构建后,
src
将不存在。您永远不应该在源代码中引用它。- 您不能将资源视为"file",它可能不会驻留在操作系统的磁盘上,并且很可能嵌入到应用程序 Jar(这是一个 Zip 文件)中。如果这还不够复杂,那么更新正在运行的 Jar 几乎是不可能的......
不要写入资源,而是考虑将其写入公共(public)位置,可以存储在 user.home
位置
关于java - 写入资源路径中的文件时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27391066/