Skip to content

Instantly share code, notes, and snippets.

@dpash
Created May 14, 2018 17:25
Show Gist options
  • Save dpash/73e629f11fd170129922f3deb469541c to your computer and use it in GitHub Desktop.
Save dpash/73e629f11fd170129922f3deb469541c to your computer and use it in GitHub Desktop.
public static void readCsv(String filePath) {
BufferedReader reader = null;
try {
List<User> users = new ArrayList<User>();
String line = "";
reader = new BufferedReader(new FileReader(filePath));
reader.readLine();
while((line = reader.readLine()) != null) {
String[] fields = line.split(",");
if(fields.length > 0) {
User user = new User();
user.setId(Integer.parseInt(fields[0]));
user.setFirstName(fields[1]);
user.setLastName(fields[2]);
users.add(user);
}
}
for(User u: users) {
System.out.printf("[userId=%d, firstName=%s, lastName=%s]\n", u.getId(), u.getFirstName(), u.getLastName());
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void readCsv(String filePath) {
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))){
reader.readLine();
List<User> users = reader.lines()
.map(line -> line.split(","))
.filter(fields -> fields.length > 0)
.forEach(this::mapToUser)
.collect(toList());
for(User u: users) {
System.out.printf("[userId=%d, firstName=%s, lastName=%s]\n", u.getId(), u.getFirstName(), u.getLastName());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@NotNull
private static User mapToUser(String[] fields) {
User user = new User();
user.setId(Integer.parseInt(fields[0]));
user.setFirstName(fields[1]);
user.setLastName(fields[2]);
return user;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment