仅使用OpenCSV部分解析CSV文件 [英] Only partialially parse a CSV file with OpenCSV

查看:106
本文介绍了仅使用OpenCSV部分解析CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV文件,要在Java中使用OpenCSV的csvreader进行解析.

I have a CSV file which I want to parse in Java with OpenCSV's csvreader.

为此,我创建了一个将信息映射到的bean对象.我的有点长,所以这是我从教程中得到的一个示例:

To do so I have created a bean object to which the information is mapped. Mine is a bit long so here's an example I got from a tutorial :

package net.viralpatel.java;

public class Country {
    private String countryName;
    private String capital;

    public String getCountryName() {
    return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }

    public String getCapital() {
        return capital;
    }

    public void setCapital(String capital) {
        this.capital = capital;
    }
}

我用来解析CSV文件并将信息映射到Bean的代码类似于以下代码:

The code I used to parse my CSV file and map the information to the bean resembles this one :

ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
strat.setType(Country.class);
String[] columns = new String[] {"countryName", "capital"};
strat.setColumnMapping(columns);

CsvToBean csv = new CsvToBean();

String csvFilename = "C:\\sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));

List list = csv.parse(strat, csvReader);

问题是我的CSV不仅包含原始数据,还包含列标题和其他数据.对于列标题,我仅通过使用:

The problem is that my CSV contains not only raw data but also column titles and other data. For the column titles, I solved the issue by only reading my file from a certain line with :

CSVReader csvReader = new CSVReader(new FileReader(csvFilename), ';', '\'', 1);

(1是开始读取的行)

其他数据主要是文件末尾(例如)整数列中的字符串.

The other data is mostly strings in (for example) integer columns at the end of the file.

例如,我有一个带有整数信息的"Max Speed"列,紧挨着一个带有整数信息的"Distance"列.但是在距离"(Distance)列的末尾是总距离,因此字符串"total:"在它旁边的最大速度"(Max Speed)列中.

For example i have a "Max Speed" column with integer information, just next to a "Distance" column with integer information too. But at the end of the "Distance" column there is the total distance, so the String "total:" is in the "Max Speed" column right next to it.

我该怎么做以确保读者忽略最后几行而只读取上面的原始信息?

What can I do to ensure that the reader ignores this last lines and only reads the raw information above?

PS:我读取的CSV文件的长度不同.因此,说在X线后停止阅读"不会解决问题.另一方面,附录"行始终相同.因此说停止在文件末尾读两行"应该有效.

PS : the CSV files I read have different lengths. So saying "stop reading after line X" won't do the trick. On the other hand the "appendix" lines are always the same. So saying "Stop reading two lines before the end of the file" should work.

非常感谢您的帮助.

推荐答案

在将其映射到bean中之前,您总是可以降低到较低的级别并检查原始字符串数组:

You can always fall to lower level and check raw string array before map it into bean like this:

ColumnPositionMappingStrategy<Country> strat = new ColumnPositionMappingStrategy<Country>();
    strat.setType(Country.class);
    String[] columns = new String[] {"countryName", "capital"};
    strat.setColumnMapping(columns);

    PublicProcessLineCsvToBean<Country> csv = new PublicProcessLineCsvToBean<Country>();

    String csvFilename = "C:\\sample.csv";
    CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
    List<Country> list = new ArrayList<Country>();

    String [] row = csvReader.readNext(); //skip header
    if(row == null) throw new RuntimeException("File is empty");
    row = csvReader.readNext();
    String [] nextRow = csvReader.readNext();
    while(row != null) {
        if(nextRow == null) break; //check what 'row' is last
        if("Total:".equalsIgnoreCase(row[1])) break; //check column for special strings

        list.add(csv.processLine(strat, row));

        row = nextRow;
        nextRow = csvReader.readNext();
    }

并公开processLine:

and to make processLine public:

public static class PublicProcessLineCsvToBean<T> extends CsvToBean<T> {

        @Override
        public T processLine(MappingStrategy<T> mapper, String[] line) throws IllegalAccessException, InvocationTargetException, InstantiationException, IntrospectionException {
            return super.processLine(mapper, line);
        }
    }

这篇关于仅使用OpenCSV部分解析CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆