使用CSVParser和Formatter处理数据,返回记录列表

3

我正在使用compile group: 'org.apache.commons', name: 'commons-csv', version: '1.5'

我原本期望下面的代码会返回3个项目,但实际上只返回了1个项目。请问应该如何修改代码才能返回3个项目?

CSVFormat format = CSVFormat.DEFAULT;
return CSVParser.parse(format.format(new Object[]{"cool", "nice", 5}), format).getRecords()

我明白它只会返回一个项目,因为只有一条记录。那么我如何将该记录的值作为列表获取?


@K.Nicholas 你是如何填充它的? - Ilya Gazman
@K.Nicholas 哦,我想我明白你的意思了。基本上我只得到了一条记录。那么我该如何将我的值作为列表返回呢? - Ilya Gazman
format.format 接受可变参数,也许你可以尝试 format.format("cool", "nice", 5) - msrd0
@msrd0 这只是Java代码格式化的问题,结果将与我所拥有的等效。 - Ilya Gazman
由于只有一条记录,您将不得不迭代值以准备好一个列表。 - Lalit Mehra
显示剩余3条评论
3个回答

1
< p > CSVParser.getRecords() 方法返回一个 List<CSVRecord>

如果您想以不同的格式获取数据,则需要在代码中转换数据。

由于 CSVRecord 实现了 Iterable<String>,因此可以遍历每个记录的列并构建所需的结构(例如,List)。 代码将类似于以下内容(注意:我不会编译示例代码):

private List<String> convertCSVRecord(
    final CSVRecord record)
{
    final List<String> returnValue = new LinkedList<String>();

    for (final String currentValue : record)
    {
        returnValue.add(currentValue);
    }

    return returnValue;
}

"

List.addAll(record) 可能有效,试试看。

"

0
你需要从中准备自己的列表。
CSVFormat format = CSVFormat.DEFAULT;
CSVRecord record = CSVParser.parse(format.format("cool", "nice", 5), format).getRecords().get(0);
Iterator iterator = record.iterator();
while(iterator.hasNext()) {
    // Add to a list
}

0

嗯,这很混乱,但它适用于处理 Object[][] 的原始问题。然而,它假设 CSVParser 中的 char[] 足够大以处理结果。

public class CsvPlay
{
    public static void main(String... args) throws Exception {
        new CsvPlay().run();
    }

    private void run() throws Exception {
        CSVFormat format = CSVFormat.DEFAULT;
        Object[][] objectLines = {{"cool"},  {"nice"}, {5}};
        System.out.println( 
            CSVParser.parse(new MyReader(format, objectLines), format).getRecords() 
        );
    }

    class MyReader extends Reader {
        private final CSVFormat format;
        private Object[][] objectLines;
        private int line = 0;
        public MyReader(CSVFormat format, Object[][] objectLines) {
            this.format = format;
            this.objectLines = objectLines;
        }
        @Override
        public int read(char[] cbuf, int off, int len) throws IOException
        {
            if ( line >= objectLines.length) return -1;
            StringBuilder sb = new StringBuilder(format.format(objectLines[line++])).append('\n');
            sb.getChars(0, sb.length(), cbuf, 0);
            return sb.length();
        }
        @Override
        public void close() throws IOException {}
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接