Skip to content

Instantly share code, notes, and snippets.

@diefferson
Created October 25, 2017 23:55
Show Gist options
  • Save diefferson/780fd15a286e96bc1bcb55c9e7b4aae3 to your computer and use it in GitHub Desktop.
Save diefferson/780fd15a286e96bc1bcb55c9e7b4aae3 to your computer and use it in GitHub Desktop.
CSV Parser Java
package br.com.diefferson;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.*;
class CSVUtils {
static <T> List<T> parse(String filePath, String divider, Class<T> classType) {
List<T> results = new ArrayList<>();
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader(filePath));
while ((line = br.readLine()) != null) {
String[] values = line.split(divider);
T object = instantiateItem(classType,values);
results.add(object);
}
}catch ( IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return results;
}
private static <T> T instantiateItem(Class<T> classType, String[] values) {
T object = null;
try {
object = classType.newInstance();
Field[] fields = classType.getDeclaredFields();
int i = 0;
for(Field field: fields){
if(!field.isAnnotationPresent(CSVIgnore.class)){
field.setAccessible(true);
switch (field.getType().getName()){
case "double":
field.setDouble(object, Double.parseDouble(values[i]));
i++;
break;
case "int":
field.setInt(object, Integer.parseInt(values[i]));
i++;
break;
case "float":
field.setFloat(object, Float.parseFloat(values[i]));
i++;
break;
default:
field.set(object, values[i]);
i++;
break;
}
}
}
} catch (IllegalAccessException | InstantiationException e) {
e.printStackTrace();
}
return object;
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CSVIgnore{}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment