Reading a CSV file as an object

The simplest CSV file looks like the file in the following illustration (lines of data separated by commas):

A simple and efficient solution to deserializing this kind of CSV file relies on the BufferedReader and String.split() methods. We can read each line from the file via BufferedReader.readLine() and split it with a comma delimiter via Spring.split(). The result (each line of content) can be stored in a List<String>. The final result will be a List<List<String>>, as follows:

public static List<List<String>> readAsObject(
Path path, Charset cs, String delimiter) throws IOException {

List<List<String>> content = new ArrayList<>();

try (BufferedReader br = Files.newBufferedReader(path, cs)) {

String line;

while ((line = br.readLine()) != null) {
String[] values = line.split(delimiter);
content.add(Arrays.asList(values));
}
}

return content;
}

If the CSV data has POJOs correspondents (for example, our CSV is the result of serializing a bunch of Melon instances), then it can be deserialized, as shown in the following example:

public static List<Melon> readAsMelon(
Path path, Charset cs, String delimiter) throws IOException {

List<Melon> content = new ArrayList<>();

try (BufferedReader br = Files.newBufferedReader(path, cs)) {

String line;

while ((line = br.readLine()) != null) {
String[] values = line.split(Pattern.quote(delimiter));
content.add(new Melon(values[0], Integer.valueOf(values[1])));
}
}

return content;
}
For complex CSV files, it is advisable to rely on dedicated libraries (for example, OpenCSV, Apache Commons CSV, Super CSV, and so on).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset