java实现CSV 字段分割

时间:2021-10-19 22:26:11

支持引号嵌套,逗号分割

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private static String[] cvsField(String line){
    List<String> fields = new LinkedList<>();
    char[] alpah = line.toCharArray();
    boolean isFieldStart = true;
    int pos = 0; int len = 0; boolean yinhao = false;
    for(char c : alpah){
      if(isFieldStart){
        len = 0;
        isFieldStart = false;
      }
      if(c == '\"'){
        yinhao = !yinhao;
      }
      if(c == ',' && !yinhao){
        fields.add(new String(alpah, pos - len, len));
        isFieldStart = true;
      }
      pos++; len++;
    }
    return fields.toArray(new String[0]);
  }

以上所述就是本文的全部内容了,希望大家能够喜欢。