This version doesn't use any fancy class-generating code; instead, it outputs Java source-files (or more accurately, a single class file, with a static public inner subclass for each non-header row in the CSV).
For the following input (borrowed from Binkan):
############
foo,bar
############
he"l\nl"o,world
cafe,babe
The output would be:
public class Out {
public static class Row1 {
public String foo = "he\"l\\nl\"o";
public String bar = "world";
}
public static class Row2 {
public String foo = "cafe";
public String bar = "babe";
}
}
And here is the code; partially adapted from Binkan's as regards line-by-line reading:
public class T {
public static void classesFromRows(String fileName, PrintWriter out, String classNamePrefix) throws Exception{
try(BufferedReader stream = new BufferedReader(new FileReader(fileName))) {
String line = null;
String[] fields = null;
int rowNum = 0;
while ((line = stream.readLine()) != null) {
if (line.isEmpty() || line.startsWith("#")) {
// do nothing
} else if (fields == null) {
fields = line.split(",");
} else {
rowNum ++;
String[] values = line.split(",");
out.println("\tpublic static class " + classNamePrefix + rowNum + " {");
for (int i=0; i<fields.length; i++) {
out.println("\t\tpublic String " + fields[i] + " = \""
+ StringEscapeUtils.escapeJava(values[i]) + "\";");
}
out.println("\t}");
}
}
}
}
// args[0] = input csv; args[1] = output file
public static void main(String[] args) throws Exception {
File outputFile = new File(args[1]);
String outputClass = outputFile.getName().replace(".java", "");
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
// missing: add a package here, if you want one
out.println("public class " + outputClass + " {");
classesFromRows(args[0], out, "Row");
out.println("}");
out.close();
}
}
I have chosen to consider all data as strings (on the bright side, I am escaping them correctly using StringEscapeUtils); with some more code, you could specify other types.