编写CSV解析器,其中未定义空位数和位置

时间:2018-12-26 06:49:05

标签: java csv generics

基本上,我需要编写一个csv解析器,该解析器将考虑用户定义的映射。同时没有定义列的顺序,并且用户可以有任意数量的列,但是Application只会考虑映射中匹配的列。

我试图创建一个映射,其中键将是用户cloumn,值将是休眠实体cloumn。

下一步将是查找是否找到条目,如果找到了下一步,则将是查找列的位置。

    try {

        List<Student> students = new ArrayList<Student>();

        String line = "";
        fileReader = new BufferedReader(new FileReader(fileName));
        line=fileReader.readLine();
        String[] headers = line.split(COMMA_DELIMITER);
        int columnCounter=0;
        for(String a : headers){// parsing the header

            String columnName=clientMapping.get(a);//gettting actual column from mapping defined by user

            if(columnName !=null){
                switch(columnName.toUpperCase()){

                case "FNAME":
                    STUDENT_FNAME=columnCounter;// finding the position of column
                    break;

                case "LNAME":
                    STUDENT_LNAME=columnCounter;
                    break;

                case "SEX" :
                    STUDENT_GENDER=columnCounter;
                    break;
                case "ID" :
                    STUDENT_ID=columnCounter;
                    break;
                case "AGE" :
                    STUDENT_AGE=columnCounter;  
                    break;

                 default :
                     System.out.println("default");

                }
            }
            columnCounter++;

        }
        //Read the file line by line starting from the second line
        while ((line = fileReader.readLine()) != null) {
            //Get all tokens available in line
            String[] tokens = line.split(COMMA_DELIMITER);
            if (tokens.length > 0) {
                //Create a new student object and fill his  data
          Student student = new Student(Long.parseLong( STUDENT_ID == -1 ? null : tokens[STUDENT_ID]),STUDENT_FNAME == -1 ? null: tokens[STUDENT_FNAME], STUDENT_LNAME == -1 ? null : tokens[STUDENT_LNAME], STUDENT_GENDER == -1 ? null:tokens[STUDENT_GENDER],STUDENT_AGE == -1 ? null: Integer.parseInt(tokens[STUDENT_AGE]));
                students.add(student);
            }
        }

它可以正常工作,但这仅适用于学生班,因为它不是通用的。

0 个答案:

没有答案