csvreader treart null为字符串“null”

p8h8hvxi  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(445)

我有一个输入csv如下

firstName,lastName
abdu,null
shah,kha

我用的是opencsv,我的代码是

File inputFile = new File("input.csv");
CsvSchema schema = CsvSchema.emptySchema().withHeader();
MappingIterator<Map<String, String>> mappingIterator = 
        new CsvMapper().readerFor(Map.class).with(schema).readValues(inputFile);

第一个Map迭代器生成以firstname和lastname作为键的Map。姓氏的值为 "null" (带引号的字符串)。有没有办法让我把它读成 null (没有引号)??

64jmpszr

64jmpszr1#

在opencsv中,您可以实现自己的csvparser,如下所示:

public static void main(String[] args) throws Exception {
    String csv = "firstName,lastName\n" +
            "abdu,null\n" +
            "shah,kha";

    CSVReader reader = new MyCSVReader(csv);

    String[] nextLine;
    while ((nextLine = reader.readNext()) != null) {
        for (String s : nextLine) {
            System.out.print(s == null ? "NULL" : s);
        }
        System.out.println();
    }
}

private static class MyCSVReader extends CSVReader {
    public MyCSVReader(String csv) {
        super(new StringReader(csv));
        parser = new CSVParser() {
            @Override
            protected String[] parseLine(String nextLine, boolean multi) throws IOException {
                String[] result = super.parseLine(nextLine, multi);
                for (int i = 0; i < result.length; ++i) {
                    if ("null".equals(result[i])) result[i] = null;
                }
                return result;
            }
        };
    }
}

相关问题