/* * Copyright (C) 2021 Christian Pierre MOMON * * This file is part of StatoolInfos, simple service statistics tool. * * StatoolInfos is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * StatoolInfos 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with StatoolInfos. If not, see . */ package fr.devinsy.statoolinfos.io; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Class CSVWriter. */ public class CSVWriter implements SpreadsheetWriter { private static final Logger logger = LoggerFactory.getLogger(CSVWriter.class); private char separator; private PrintWriter out; private boolean isNewline; /** * Instantiates a new CSV writer. * * @param file * the file * @param separator * the separator * @throws UnsupportedEncodingException * the unsupported encoding exception * @throws FileNotFoundException * the file not found exception */ public CSVWriter(final File file, final char separator) throws UnsupportedEncodingException, FileNotFoundException { this.separator = separator; this.out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); this.isNewline = true; } /** * Close. * * @throws FileNotFoundException * * @throws IOException * Signals that an I/O exception has occurred. */ @Override public void close() throws FileNotFoundException, IOException { IOUtils.closeQuietly(this.out); } /** * Escape. * * @param string * the string * @return the string */ private String escape(final String string) { String result; if (string == null) { result = null; } else { if (StringUtils.containsAny(string, ',', '\n', '"', this.separator)) { result = String.format("\"%s\"", string); } else { result = string; } } // return result; } /** * Write cell. * * @param content * the content */ @Override public void writeCell(final String content) { if (this.isNewline) { this.isNewline = false; } else { this.out.print(this.separator); } this.out.print(StringUtils.defaultIfBlank(escape(content), "")); } /** * Write endpage. */ @Override public void writeEndpage() { this.out.println(); } /** * Write end row. * * @throws IOException */ @Override public void writeEndRow() { this.out.println(); this.isNewline = true; } }