All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.bloodshura.ignitium.cfg.csv.CsvWriter Maven / Gradle / Ivy

Go to download

A collection of configuration and serialization readers and writers, like JSON, internationalization (I18n), and CSV.

There is a newer version: 1.0.1
Show newest version
package com.github.bloodshura.ignitium.cfg.csv;

import com.github.bloodshura.ignitium.charset.Encoding;
import com.github.bloodshura.ignitium.charset.TextBuilder;
import com.github.bloodshura.ignitium.io.stream.TextWriter;
import com.github.bloodshura.ignitium.resource.OutputResource;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.OutputStream;

public class CsvWriter extends CsvSpecification implements AutoCloseable {
	private final TextWriter writer;

	public CsvWriter(@Nonnull OutputResource resource) throws IOException {
		this(resource, null);
	}

	public CsvWriter(@Nonnull OutputResource resource, @Nullable Encoding encoding) throws IOException {
		this(new TextWriter(resource, encoding));
	}

	public CsvWriter(@Nonnull OutputStream output) {
		this(output, null);
	}

	public CsvWriter(@Nonnull OutputStream output, @Nullable Encoding encoding) {
		this(new TextWriter(output, encoding));
	}

	public CsvWriter(@Nonnull TextWriter writer) {
		this.writer = writer;
	}

	@Override
	public void close() throws IOException {
		writer.close();
	}

	public void write(@Nonnull Csv csv) throws IOException {
		CsvEntry header = csv.getHeader();

		if (header != null) {
			write(header);
		}

		for (CsvEntry entry : csv) {
			write(entry);
		}
	}

	public void write(@Nonnull CsvEntry entry) throws IOException {
		TextBuilder builder = new TextBuilder().setSeparator(getSeparator());

		for (String s : entry) {
			if (s.indexOf(getSeparator()) != -1) {
				builder.append(getQuote() + s + getQuote());
			} else {
				builder.append(s);
			}
		}

		writer.writeln(builder);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy