'Saving info with matching header (CSV) where info can be String or ArrayList (Hashmap)
I'm creating a method where it creates a csv file with a header if the file doesn't exist, and appends info if the file already exists. I used HashMap to gather all info together before writing it on the csv file so that the appropriate info would go into the appropriate column (i.e. to the column with the matching header).
But the problem is some of my information are not ArrayList <String> but rather just a String. Casting String into ArrayList <String> won't work. Is there a way to get around this? I'd like it to be able to match the header and find the appropriate column to save.
String csvFilePath = "./idk.csv";
File f = new File(csvFilePath);
CSVPrinter csvPrinter = null;
if (!f.exists()) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(csvFilePath,false));
csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(TagCategories.class));
csvPrinter.close();
System.out.println("file doesn't exist so new csv file created");
} catch (IOException e) {
e.printStackTrace();
}
} else {
BufferedWriter writer;
try {
writer = new BufferedWriter(new FileWriter(csvFilePath, true));
csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
String imagefilepath = MenuBar.subPathList.get(MenuBar.imgIndex);
String imagefilename = new File(imagefilepath).getName();
// Here is where the problem is
HashMap<TagCategories, ArrayList <String>> m = new HashMap<>();
m.put(TagCategories.FILE_PATH, (ArrayList<String>) Arrays.asList(imagefilepath));
m.put(TagCategories.FILE_NAME, (ArrayList<String>) Arrays.asList(imagefilename));
m.put(TagCategories.GROUP, mPanel.getSelectedGROUP());
//m.put(TagCategories.ID, Arrays.asList(mPanel.getSelectedID()));
//m.put(TagCategories.NUM, Arrays.asList(mPanel.getSelectedNUM()));
csvPrinter.printRecord(Arrays.asList(TagCategories.values())
.stream()
.map(header -> m.get(header))
.collect(Collectors.toList()));
} catch (IOException e) {
e.printStackTrace();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
