com.paolodragone.util.io.datasets.tsv.TsvDataSetWriter.java Source code

Java tutorial

Introduction

Here is the source code for com.paolodragone.util.io.datasets.tsv.TsvDataSetWriter.java

Source

/*
 * 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.DataSetWriter;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.util.stream.Stream;

/**
 * @author Paolo Dragone
 */
public class TsvDataSetWriter implements DataSetWriter {

    private CSVFormat format;
    private CSVPrinter csvPrinter;

    TsvDataSetWriter(CSVFormat format) {
        this.format = format;
    }

    @Override
    public void open(Writer writer) throws IOException {
        if (!isOpen()) {
            csvPrinter = new CSVPrinter(writer, format);
        }
    }

    @Override
    public boolean isOpen() {
        return csvPrinter != null;
    }

    @Override
    public void writeRecords(Writer fileWriter, Stream<Object[]> records) throws IOException {
        open(fileWriter);
        records.forEachOrdered(this::tryWriteRecord);
        close();
    }

    @Override
    public void writeRecord(Object... record) throws IOException {
        if (!isOpen()) {
            throw new IllegalStateException("DataSetWriter is not opened.");
        }
        csvPrinter.printRecord(record);
    }

    private void tryWriteRecord(Object... record) {
        try {
            writeRecord(record);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    @Override
    public void close() throws IOException {
        if (csvPrinter != null) {
            csvPrinter.flush();
            csvPrinter.close();
            csvPrinter = null;
        }
    }
}