【问题标题】:How can Univocity Parsers read a .csv file's data properly when there are lines at the end that are not part of the .csv data?当末尾有不属于 .csv 数据的行时,Univocity 解析器如何正确读取 .csv 文件的数据?
【发布时间】:2016-03-29 14:24:20
【问题描述】:

当末尾有不属于 .csv 数据的行时,Univocity 解析器如何正确读取 .csv 文件的数据?

文件末尾的注释被解析为 .csv 数据。

代码和堆栈跟踪如下。

任何帮助将不胜感激。

import com.univocity.parsers.csv.CsvParserSettings;
import com.univocity.parsers.common.processor.*;
import com.univocity.parsers.csv.*;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.IllegalStateException;
import java.lang.String;
import java.util.List;


public class UnivocityParsers {

public Reader getReader(String relativePath) {
    try {
        return new InputStreamReader(this.getClass().getResourceAsStream(relativePath), "Windows-1252");
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Unable to read input", e);
    }
}


public void columnSelection() {
    RowListProcessor rowProcessor = new RowListProcessor();
    CsvParserSettings parserSettings = new CsvParserSettings();

    parserSettings.setRowProcessor(rowProcessor);
    parserSettings.setHeaderExtractionEnabled(true);
    parserSettings.setLineSeparatorDetectionEnabled(true);
    parserSettings.setSkipEmptyLines(true);

    // Here we select only the columns "Price", "Year" and "Make".
    // The parser just skips the other fields
    parserSettings.selectFields("AUTHOR", "ISBN");

    CsvParser parser = new CsvParser(parserSettings);
    parser.parse(getReader("list2.csv"));

    List<String[]> rows = rowProcessor.getRows();

    String[] strings = rows.get(0);

    System.out.print(strings[0]);

}


public static void main(String arg[]) {

    UnivocityParsers univocityParsers = new UnivocityParsers();

    univocityParsers.columnSelection();


}


}

这是正在解析的文件:

List of books by Author - Created today
"REVIEW_DATE","AUTHOR","ISBN","DISCOUNTED_PRICE"
"1985/01/21","Douglas Adams",0345391802,5.95
"1990/01/12","Douglas Hofstadter",0465026567,9.95
"1998/07/15","Timothy ""The Parser"" Campbell",0968411304,18.99
"1999/12/03","Richard Friedman",0060630353,5.95
"2001/09/19","Karen Armstrong",0345384563,9.95
"2002/06/23","David Jones",0198504691,9.95
"2002/06/23","Julian Jaynes",0618057072,12.50
"2003/09/30","Scott Adams",0740721909,4.95
"2004/10/04","Benjamin Radcliff",0804818088,4.95
"2004/10/04","Randel Helms",0879755725,4.50

 **This is the top author list.

【问题讨论】:

  • 您提到了堆栈跟踪,但我没有看到。你刚才说的是文件吗?最后一行在解析后的样子是什么?

标签: java parsing csv


【解决方案1】:

对于您提供的输入文件,需要以下附加设置:

第一:

    parserSettings.setNumberOfRowsToSkip(1);

这告诉解析器忽略第一行,否则它将用作标题行。

第二:

    parserSettings.getFormat().setComment('*');

您的最后一行包含以星号开头的注释。此设置使解析器跳过包含此类内容的行。

这就是你所需要的。

【讨论】:

    猜你喜欢
    • 2016-02-06
    • 2018-05-11
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2016-03-20
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多