Java tutorial
/* * Copyright Paolo Dragone 2014 * * This file is part of WiktionarySemanticNetwork. * * WiktionarySemanticNetwork is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WiktionarySemanticNetwork is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with WiktionarySemanticNetwork. If not, see <http://www.gnu.org/licenses/>. */ package com.paolodragone.util.io.datasets.tsv; import com.paolodragone.util.io.datasets.DataColumn; import com.paolodragone.util.io.datasets.DataRecord; import com.paolodragone.util.io.datasets.DataSetReader; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import java.io.Reader; import java.util.Iterator; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * @author Paolo Dragone */ public class TsvDataSetReader implements DataSetReader { private final CSVFormat format; private final DataColumn[] header; private CSVParser parser; TsvDataSetReader(DataColumn[] header, CSVFormat format) { this.format = format; this.header = header; } @Override public void open(Reader reader) throws Exception { if (!isOpen()) { parser = new CSVParser(reader, format); } } @Override public boolean isOpen() { return parser != null; } @Override public Stream<? extends DataRecord> getRecordStream() { if (!isOpen()) { throw new IllegalStateException("This reader is not opened."); } return StreamSupport.stream(spliterator(), false); } @Override public void close() throws Exception { if (parser != null) { parser.close(); parser = null; } } @Override public Iterator<DataRecord> iterator() { if (!isOpen()) { throw new IllegalStateException("This reader is not opened."); } return new TsvDataRecordIterator(parser.iterator()); } private class TsvDataRecordIterator implements Iterator<DataRecord> { private final Iterator<CSVRecord> csvRecordIterator; public TsvDataRecordIterator(Iterator<CSVRecord> csvRecordIterator) { this.csvRecordIterator = csvRecordIterator; } @Override public boolean hasNext() { return csvRecordIterator.hasNext(); } @Override public DataRecord next() { return new TsvDataRecord(csvRecordIterator.next(), header); } @Override public void remove() { csvRecordIterator.remove(); } } }