Skip to content

Instantly share code, notes, and snippets.

@owlstead
Last active August 16, 2021 10:43
Show Gist options
  • Save owlstead/33b4e73ac73c4cecaeca3d5b1c6bd1a3 to your computer and use it in GitHub Desktop.
Save owlstead/33b4e73ac73c4cecaeca3d5b1c6bd1a3 to your computer and use it in GitHub Desktop.
Code share for StackOverflow CSV example
package com.stackoverflow;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
public class Csv {
public Csv() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws IOException {
File file = new File("StatesAbbreviations.csv");
var stateToAbbreviation = new HashMap<String, String>();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
String abbrevInfo;
while ((abbrevInfo = bufferedReader.readLine()) != null) {
String[] stats = abbrevInfo.split(",");
// stats[0] may be empty, but never null, no check required
stateToAbbreviation.put(stats[0], stats[1]);
}
} catch (IOException e) {
// replace with your own checked exception
throw new RuntimeException("Could not read abbreviations from CSV file", e);
}
for (String key: stateToAbbreviation.keySet()){
System.out.println(key +" = "+stateToAbbreviation.get(key));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment