首页 > 解决方案 > Apache 公用 CSV | 如何在字段中忽略/包含分号、逗号?

问题描述

我正在尝试解析日志文件并将其存储在 CSV 文件中。这是下面的示例行:

218.1.111.50 - - [13/Mar/2005:10:36:11 -0500] "GET http://www.yahoo.com/ HTTP/1.1" 403 2898 "-" "Mozilla/4.0 (compatible; MSIE 4.01; Windows 95)"

为此,我正在使用Apache commons CSV库。问题是某些字段在特殊字符中具有;其值,并且它们被解释为分隔符。

例如,如果我们看一下字段 value Mozilla/4.0 (compatible; MSIE 4.01; Windows 95)。由于;.

在此处输入图像描述

我不知道解决这个问题的理想方法。请看下面,与我使用的库相关的代码快照:

  CSVPrinter printer = new CSVPrinter(writer, CSVFormat.DEFAULT
                    .withHeader(HEADERS));
//
//
Matcher m = p.matcher(line);
                    Date date=formatter.parse(m.group("Time"));

            try {

                printer.printRecord(date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), m.group("NetworkSrcIpv4"),
                        m.group("ApplicationHttpStatus"),m.group("ApplicationLen"),m.group("ApplicationHttpUserAgent"),
                        m.group("ApplicationHttpQueryString"));

                printer.flush();

            } catch (IOException e) {

                e.printStackTrace();

            }
//

是否有可能自动忽略;,或者用一些不会影响所需结果的值替换它们?有什么我可以添加的选项CSVprinter吗?

感谢您的反馈意见。

标签: javacsv

解决方案


您可以将 TAB 配置为分隔符,而不是使用 DEFAULT 分隔符 -

CSVPrinter printer = new CSVPrinter(writer, CSVFormat.TDF.withHeader(HEADERS));

https://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html#TDF


推荐阅读