-
Notifications
You must be signed in to change notification settings - Fork 1
Description
Problem
ezload
provides a way to read CSV checking its format. But it is too focused on writing to a database when it is also useful to just read CSV. Actually, to read CSV you have to do this
while ((raw = bufferedReader.readLine()) != null) {
Line parsedLine = this.parser.parse(raw);
for (Value value : parsedLine.values()) {
value.accept(new SomeAction(...));
}
}
In this example, users have to implement an action to take values from csv for each line.
The solution I'd like
provide a ReadCsv
to read easily CSV lines by columns. Maybe something like this
ReadCsv read = new ReadImplementation(Parser, Path);
while(read.hasNext()) Object o = read.next().get(0);
The problem of the example above is that a line has multiple columns with different types and we don't want to cast. So, considering that every time we read a line the parser checks its format. When we retrieve a value, we can assume that the line is correct. Otherwise, an exception should have been thrown and in that case, we didn't even have the chance to read a column from a wrong line. Also, we already know the types that ezload
allows to read. So we can do this
ReadCsv read = new ReadImplementation(Parser, Path);
read.stream().forEach(
line -> line.get(0).intValue(); line.get(1).stringValue(); line.get(2).dateValue();
);
When we call dateValue
and that column is an int
we can throw an exception or try to parse the value into a LocalTime
.
All these tries are not elegant enough. Another option is to have a Map<String, ?>
for each type. Then the user can get them just calling them by its name
int i = line.intFrom("column name");
String s = line.stringFrom("another column name");
double d = line.doubleFrom("you got the idea right?");
Now if the user asks for an int
that has been defined as String
this throws an exception because that column name does not exist on int's map. Then the full example is
ReadCsv read = new ReadImplementation(Parser, Path, StandarCharset);
while(read.hasNext()) {
MapLine line = read.next();
int i = line.intFrom("column name");
String s = line.stringFrom("another column name");
double d = line.doubleFrom("you got the idea right?");
}