如何从CSV标头创建pojo类

时间:2015-11-18 11:33:18

标签: java spring csv pojo

我有CSV文件,其中包含firstName,LastName,salary等字段名称。我希望从此文件生成pojo类。在CSV文件中没有数据类型信息,因此请考虑所有字段都是字符串类型。 有没有办法在构建时从csv文件创建pojo类?

下面是CSV文件。

employees.csv

empId,firstName,lastName,title,salary 

从此我想生成pojo,如下所示

class employees{
   private string empId;
   private string firstName;
   private string lastName;
   private string title;
   private string salary;

   // getters and setters 
    .
    .
    .
   //toString() method
}

2 个答案:

答案 0 :(得分:1)

  

您可以使用OpenCSV处理CSV文件并使用   javassist动态创建Java类。

他们各自的网站上都有例子。

  

我强烈建议您查看stackoverflow thread - Generate java class from csv file

我希望它有所帮助!

答案 1 :(得分:1)

最后我根据要求得到了解决方案我通过设置classname,parentDirectory,packageName和CSV file手动创建pojo类。它将使用fields,setter,getters和toString方法在指定的目录文件中创建.java。但是如果文件中只有一个标题行,它将起作用 代码在下面

 public static void createPojoFromCsvHeader(File csvInputFile,String directoryOfjavaFile,String packageName,String className)
  {    
      try(BufferedReader stream = new BufferedReader(new FileReader(csvInputFile))) {
        String packagePath=packageName.replace(".","/");
        String javaOutputDirPath=directoryOfjavaFile+"/"+packagePath+"/";
        System.out.println("creating directory ->"+javaOutputDirPath);
        File f=new File(javaOutputDirPath);
        if(f.mkdirs()){
            System.out.println("directory :"+javaOutputDirPath+" created succesfully..");
        }else{
            System.out.println("directory :"+javaOutputDirPath+" already exist..");
        }
        String javaOutputFilePath=directoryOfjavaFile+"/"+packagePath+"/"+className+".java";
        File javaOutPutFile=new File(javaOutputFilePath);
        javaOutPutFile.createNewFile();
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(javaOutputFilePath)));          
        System.out.println("generating class..");            
        out.println("package "+packageName+";");
        out.println("public class " + className + " {");
        String line = null;
        String[] fields = null;
        int rowNum = 0;
        while ((line = stream.readLine()) != null) {
            if (line.isEmpty() || line.startsWith("#")) {
                continue;
            } else {
                if (fields == null) {
                    fields = line.split(",");
                }

                rowNum++;
                String[] values = line.split(",");
                for (int i = 0; i < fields.length; i++) {
                    out.println("\t\tprivate String " + fields[i] + " = \""+ StringEscapeUtils.escapeJava(values[i])+ "\";");
                }

                for (int i = 0; i < fields.length; i++) {
                    String tempField=StringEscapeUtils.escapeJava(values[i]).substring(0, 1).toUpperCase()+StringEscapeUtils.escapeJava(values[i]).substring(1);

                    //getter method
                    out.println("");
                    out.println("\t\tpublic String  get"+tempField+ "(){");
                    out.println("\t\t\treturn this."+StringEscapeUtils.escapeJava(values[i])+";");
                    out.println("\t\t}");
                    //setter method
                    out.println("\t\tpublic void  set"+tempField+"(String "+ StringEscapeUtils.escapeJava(values[i])+"){");
                    out.println("\t\t\t this."+StringEscapeUtils.escapeJava(values[i])+" = "+ StringEscapeUtils.escapeJava(values[i])+";");
                    out.println("\t\t}");
                }

                out.println("");
                out.println("// toString() Method");
                out.println("\t\t public String toString(){");
                StringBuffer buffer=new StringBuffer();
                buffer.append("\"{");
                for (int i = 0; i < fields.length; i++) {
                    buffer.append("\\\""+StringEscapeUtils.escapeJava(values[i])+"\\\"=\"+"+StringEscapeUtils.escapeJava(values[i]));
                    if(i < fields.length-1){
                        buffer.append("+\",");
                    }
                    else{
                        buffer.append("+\"");
                    }
                }
                buffer.append("}\";");
                out.println("\t\t\t return "+buffer);
                out.println("\t\t}");
            }
            out.println("}");
            out.close();
        }
        System.out.println("no of lines fetch from csv :"+rowNum);
        }catch(IOException e)
      {
            e.printStackTrace();
      }

  }