java 如何将 ArrayList<Object> 写入 csv 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35057456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:41:15  来源:igfitidea点击:

How to write ArrayList<Object> to a csv file

javacsvarraylistopencsv

提问by Maverick

I have a ArrayList<Metadata>and i want to know if there is a Java API for working with CSV files which has a write method which accepts a ArrayList<> as parameter similar to LinqToCsv in .Net. As i know OpenCSVis available but the CsvWriter class doesn't accept a collection. My Metadata Class is

我有一个ArrayList<Metadata>,我想知道是否有一个 Java API 用于处理 CSV 文件,它有一个 write 方法,它接受一个 ArrayList<> 作为类似于 .Net 中的 LinqToCsv 的参数。据我所知,OpenCSV可用,但 CsvWriter 类不接受集合。我的元数据类是

public class Metadata{
    private String page;
    private String document;
    private String loan;
    private String type;
}
ArrayList<Metadata> record = new ArrayList<Metadata>();

once i populate the record, i want to write each row into a csv file. Please suggest.

填充记录后,我想将每一行写入一个 csv 文件。请建议。

回答by Henrik

Surely there'll be a heap of APIs that will do this for you, but why not do it yourself for such a simple case? It will save you a dependency, which is a good thing for any project of any size.

肯定会有一堆 API 可以为您执行此操作,但是为什么不为这样一个简单的案例自己做呢?它将为您节省一个依赖项,这对于任何规模的任何项目都是一件好事。

Create a toCsvRow()method in Metadatathat joins the strings separated by a comma.

创建一个toCsvRow()方法Metadata来连接由逗号分隔的字符串。

public String toCsvRow() {
    return Stream.of(page, document, loan, type)
            .map(value -> value.replaceAll("\"", "\"\""))
            .map(value -> Stream.of("\"", ",").anyMatch(value::contains) ? "\"" + value + "\"" : value)
            .collect(Collectors.joining(","));
}

Collect the result of this method for every Metadataobject separated by a new line.

为每个Metadata由新行分隔的对象收集此方法的结果。

String recordAsCsv = record.stream()
        .map(Metadata::toCsvRow)
        .collect(Collectors.joining(System.getProperty("line.separator")));


EDITShould you not be so fortunate as to have Java 8 and the Stream API at your disposal, this would be almost as simple using a traditional List.

编辑如果您没有幸运地拥有 Java 8 和 Stream API 可供您使用,那么使用传统的 List 几乎同样简单。

public String toCsvRow() {
    String csvRow = "";
    for (String value : Arrays.asList(page, document, loan, type)) {
        String processed = value;
        if (value.contains("\"") || value.contains(",")) {
            processed = "\"" + value.replaceAll("\"", "\"\"") + "\"";
        }
        csvRow += "," + processed;
    }
    return csvRow.substring(1);
}

回答by Arnaud

By using CSVWriter, you could convert the ArrayListto an array, and pass that to the writer .

通过使用CSVWriter,您可以将 转换ArrayList为数组,并将其传递给 writer 。

csvWriter.writeNext(record.toArray(new String[record.size()]));

回答by Scott Conway

If you have an ArrayList of Objects (Metadata in your case) you would use the BeanToCSV instead of the CSVWriter.

如果您有对象的 ArrayList(在您的情况下为元数据),您将使用 BeanToCSV 而不是 CSVWriter。

You can look at the BeanToCSVTest in the opencsv source codefor examples of how to use it.

您可以查看opencsv 源代码中的 BeanToCSVTest以了解如何使用它的示例。