I have a Swing app that requires reading and writing to a file in CSV format. I have this file at src/main/resources/dictData.dat
Currently, when I execute the executable jar via
java -jar dictionary-jar-with-dependencies.jar
and try to execute a save operation, I get
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)**
Here, I have a method that wirtes the contents of a Map
structure to a CSV file using Apache CSV library.
The topmost message on the stacktrace is at the dataWriter.flush()
method within the 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();
}
}
}
Strangely, I had a similar issue with reading the file from the same location. It was resolved by converting the file open to a stream via
//Open file connection and read stream
dataUrl = classLoader.getResource(dictionaryFile);
dataReader = new InputStreamReader(dataUrl.openStream());
Note that this only occurs when executing via java -jar
, and this application works perfectly when run inside the IDE.