org.apache.commons.csv.CSVPrinter

Here are the examples of the java api org.apache.commons.csv.CSVPrinter taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

178 Examples 7

19 Source : CSV.java
with GNU General Public License v3.0
from salimkanoun

public clreplaced CSV {

    private StringBuilder content;

    private CSVPrinter csv;

    private DateFormat df = new SimpleDateFormat("MMddyyyy");

    public CSV() {
        content = new StringBuilder();
        try {
            csv = new CSVPrinter(content, CSVFormat.DEFAULT);
            csv.printRecord(new Object[] { "Old patient name", "Old patient id", "New patient name", "New patient id", "Old study date", "Old study description", "New study description", "Nb series", "Nb instances", "Size", "Study instance uid" });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addStudy(String oldPatientName, String oldPatientId, String newPatientName, String newPatientId, Date oldStudyDate, String oldStudyDesc, String newStudyDesc, int nbSeries, int nbInstances, int size, String studyInstanceUid) {
        try {
            csv.printRecord(new Object[] { oldPatientName, oldPatientId, newPatientName, newPatientId, df.format(oldStudyDate), oldStudyDesc, newStudyDesc, nbSeries, nbInstances, size, studyInstanceUid });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getCsv() {
        return content.toString();
    }
}

19 Source : CSVResultWriter.java
with Apache License 2.0
from Remper

/**
 * Writes CSV with the results to disk
 *
 * @author Yaroslav Nechaev ([email protected])
 */
public clreplaced CSVResultWriter implements ResultWriter {

    private final CSVPrinter csvWriter;

    public CSVResultWriter(File output) throws IOException {
        csvWriter = new CSVPrinter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(output)), Charsets.UTF_8), CSVFormat.DEFAULT);
    }

    @Override
    public void write(String resourceId, List<DumpResource.Candidate> candidates, Long trueUid) {
        try {
            for (DumpResource.Candidate candidate : candidates) {
                csvWriter.printRecord(resourceId, candidate.uid, candidate.score, candidate.is_alignment);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void flush() {
        try {
            csvWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

19 Source : CsvWriter.java
with Apache License 2.0
from HongZhaoHua

/**
 * CSV写出器
 *
 * @author Birdy
 */
public clreplaced CsvWriter extends CsvContext {

    private CSVPrinter outputStream;

    public CsvWriter(OutputStream outputStream, CodecDefinition definition) {
        super(definition);
        try {
            OutputStreamWriter buffer = new OutputStreamWriter(outputStream, StringUtility.CHARSET);
            this.outputStream = new CSVPrinter(buffer, FORMAT);
        } catch (Exception exception) {
            throw new RuntimeException(exception);
        }
    }

    public CSVPrinter getOutputStream() {
        return outputStream;
    }
}

19 Source : CSVPrinterWrapper.java
with GNU General Public License v3.0
from Alcidauk

/**
 * CineLog Copyright 2018 Pierre Rognon
 *
 * This file is part of CineLog.
 * CineLog 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.
 *
 * CineLog 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 CineLog. If not, see <https://www.gnu.org/licenses/>.
 */
clreplaced CSVPrinterWrapper {

    private CSVPrinter csvPrinter;

    public CSVPrinterWrapper(Appendable out, Clreplaced<? extends Enum<?>> headers) throws IOException {
        this.csvPrinter = new CSVPrinter(out, CSVFormat.DEFAULT.withHeader(headers).withQuote('`').withDelimiter('§'));
    }

    public void printRecord(Object... values) throws IOException {
        csvPrinter.printRecord(values);
    }

    public void close() throws IOException {
        csvPrinter.close();
    }

    public void flush() throws IOException {
        csvPrinter.flush();
    }
}

18 Source : NamespacePanel.java
with Apache License 2.0
from wavefrontHQ

/**
 * The major panel of wftop that displays namespaces, pps, access %, etc.
 *
 * @author Clement Pang ([email protected]).
 */
public abstract clreplaced NamespacePanel extends Panel {

    protected final Label globalPPS = new Label("");

    protected final Label connectivityStatus = new Label("");

    protected final Label samplingRate = new Label("");

    protected final Label path = new Label("> ");

    protected final Label stopwatchTime = new Label("");

    protected final Panel header, footer;

    protected Listener listener = null;

    protected Table<String> table;

    protected Map<String, Node> labelToNodeMap = new HashMap<>();

    protected int sortIndex = 1;

    protected boolean reverseSort = true;

    protected Button configBtn, stopStartBtn;

    protected String exportFile = null;

    protected String rootPath = null;

    protected CSVPrinter csvPrinter;

    public NamespacePanel(SpyConfigurationPanel panel, MultiWindowTextGUI gui) {
        this.setLayoutManager(new BorderLayout());
        // header.
        header = new Panel(new BorderLayout());
        header.addComponent(globalPPS.withBorder(Borders.singleLine()).setLayoutData(BorderLayout.Location.CENTER));
        header.addComponent(connectivityStatus.withBorder(Borders.singleLine()).setLayoutData(BorderLayout.Location.LEFT));
        header.addComponent(samplingRate.withBorder(Borders.singleLine()).setLayoutData(BorderLayout.Location.RIGHT));
        header.addComponent(path.setLayoutData(BorderLayout.Location.BOTTOM));
        this.addComponent(header.setLayoutData(BorderLayout.Location.TOP));
        this.table = new Table<String>("Namespace") {

            @Override
            public Result handleKeyStroke(KeyStroke keyStroke) {
                Result result = super.handleKeyStroke(keyStroke);
                if (result != Result.UNHANDLED) {
                    return result;
                }
                if (keyStroke.getKeyType() == KeyType.Home) {
                    table.setSelectedRow(0);
                    invalidate();
                    return Result.HANDLED;
                } else if (keyStroke.getKeyType() == KeyType.End) {
                    table.setSelectedRow(table.getTableModel().getRowCount() - 1);
                    invalidate();
                    return Result.HANDLED;
                }
                return Result.UNHANDLED;
            }
        };
        this.table.setCellSelection(false);
        this.table.setSelectAction(() -> {
            if (listener != null) {
                if (this.table.getSelectedRow() == 0) {
                    listener.goUp();
                } else {
                    Node node = this.labelToNodeMap.get(this.table.getTableModel().getRow(this.table.getSelectedRow()).get(0));
                    if (node != null) {
                        listener.selectElement(node);
                    }
                }
            }
        });
        this.addComponent(table.setLayoutData(BorderLayout.Location.CENTER).withBorder(Borders.singleLine()));
        footer = new Panel(new LinearLayout(Direction.HORIZONTAL));
        configBtn = new Button("Config");
        configBtn.addListener(button -> {
            gui.addWindowAndWait(panel);
        });
        footer.addComponent(configBtn);
        Button sortLeftBtn = new Button("<- Sort");
        sortLeftBtn.addListener(button -> {
            if (listener != null) {
                listener.sortLeft();
            }
        });
        footer.addComponent(sortLeftBtn);
        Button sortRightBtn = new Button("Sort ->");
        sortRightBtn.addListener(button -> {
            if (listener != null) {
                listener.sortRight();
            }
        });
        footer.addComponent(sortRightBtn);
        Button reverseSortBtn = new Button("Reverse");
        reverseSortBtn.addListener(button -> {
            if (listener != null) {
                listener.reverseSort();
            }
        });
        footer.addComponent(reverseSortBtn);
        stopStartBtn = new Button("Stop/Start");
        stopStartBtn.addListener(button -> {
            if (listener != null) {
                listener.onStopStart();
            }
        });
        footer.addComponent(stopStartBtn);
        Button exitBtn = new Button("Exit");
        exitBtn.addListener(button -> {
            if (listener != null) {
                listener.onExit();
            }
        });
        footer.addComponent(exitBtn);
        this.addComponent(footer.setLayoutData(BorderLayout.Location.BOTTOM));
    }

    /**
     * Compares nodes based on columns.
     *
     * @return Comparison value returned.
     */
    protected abstract Comparator<Node> getComparator();

    /**
     * Add first row (to go up a folder).
     */
    protected abstract void addFirstRow(Node root, double factor, Collection<Node> nodes, Snapshot snapshot, boolean takeSnapshot);

    /**
     * Now sort and add the nodes for this folder.
     */
    protected abstract void addNodes(Node root, double factor, Collection<Node> nodes, Snapshot snapshot, String selectedLabel, boolean takeSnapshot);

    /**
     * Display global Points per Second (spy on Points) or Creations per Second (spy on Id Creation).
     *
     * @param factor Multiply by backend count to accurately display pps/cps.
     * @param rate   Used to get 1m, 5m, 15m intervals.
     */
    public abstract void setGlobalPPS(double factor, Meter rate);

    /**
     * Create CSV file for exporting data.
     */
    public abstract void setUpCSVWriter();

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    public int getSortIndex() {
        return sortIndex;
    }

    public void setSortIndex(int sortIndex) {
        // remove arrow from existing column label.
        String columnLabel = this.table.getTableModel().getColumnLabel(this.sortIndex);
        this.table.getTableModel().setColumnLabel(this.sortIndex, columnLabel.substring(0, columnLabel.length() - 4));
        // set the sort index.
        this.sortIndex = sortIndex;
        // add arrow.
        columnLabel = this.table.getTableModel().getColumnLabel(sortIndex);
        this.table.getTableModel().setColumnLabel(sortIndex, columnLabel + (reverseSort ? " [↑]" : " [↓]"));
    }

    public void toggleSortOrder() {
        this.reverseSort = !this.reverseSort;
        String columnLabel = this.table.getTableModel().getColumnLabel(this.sortIndex);
        this.table.getTableModel().setColumnLabel(this.sortIndex, columnLabel.substring(0, columnLabel.length() - 4));
        columnLabel = this.table.getTableModel().getColumnLabel(sortIndex);
        this.table.getTableModel().setColumnLabel(sortIndex, columnLabel + (reverseSort ? " [↑]" : " [↓]"));
    }

    public void setVisibleRows(int count) {
        this.table.setVisibleRows(count);
    }

    public void renderNodes(Node root, double factor, Collection<Node> nodes, boolean takeSnapshot) {
        synchronized (table) {
            @Nullable
            String selectedLabel = null;
            if (table.getSelectedRow() >= 0 && table.getTableModel().getRowCount() > 0) {
                List<String> selectedRow = table.getTableModel().getRow(table.getSelectedRow());
                selectedLabel = selectedRow.get(0);
            }
            int count = table.getTableModel().getRowCount();
            for (int i = 0; i < count; i++) {
                table.getTableModel().removeRow(0);
            }
            labelToNodeMap.clear();
            Snapshot snapshot = root.getLag().getSnapshot();
            addFirstRow(root, factor, nodes, snapshot, takeSnapshot);
            addNodes(root, factor, nodes, snapshot, selectedLabel, takeSnapshot);
        }
    }

    public void setExportData(boolean exportData, String exportFile) {
        if (exportData) {
            footer.removeComponent(configBtn);
            footer.removeComponent(stopStartBtn);
            header.addComponent(stopwatchTime.withBorder(Borders.singleLine()).setLayoutData(BorderLayout.Location.TOP));
            this.exportFile = exportFile;
            setUpCSVWriter();
        }
    }

    public void setStopwatchTime(long time) {
        this.stopwatchTime.setText("Time: " + time + " Seconds");
    }

    public void setSamplingRate(double rate) {
        this.samplingRate.setText("Sampling: " + (rate * 100) + "%");
    }

    public void setConnecting() {
        connectivityStatus.setForegroundColor(TextColor.ANSI.BLUE);
        connectivityStatus.setText("CONNECTING...");
    }

    public void setConnectionError(String string) {
        connectivityStatus.setForegroundColor(TextColor.ANSI.RED);
        connectivityStatus.setText(string == null ? "DISCONNECTED" : string);
    }

    public void setPath(String path, boolean limited) {
        this.path.setText("> " + path);
        if (limited) {
            this.path.setForegroundColor(TextColor.ANSI.RED);
        } else {
            this.path.setForegroundColor(TextColor.ANSI.BLACK);
        }
    }

    /**
     * @param path Displayed path for exporting data.
     */
    public void setRootPath(String path) {
        String[] temp = path.split("\\s+");
        if (temp.length > 0)
            this.rootPath = temp[temp.length - 1];
    }

    @VisibleForTesting
    public String getRootPath() {
        return this.rootPath;
    }

    public void setConnected() {
        connectivityStatus.setForegroundColor(TextColor.ANSI.GREEN);
        connectivityStatus.setText("CONNECTED");
    }

    public interface Listener {

        void onExit();

        void onStopStart();

        void sortLeft();

        void sortRight();

        void reverseSort();

        void selectElement(Node<?> element);

        void goUp();
    }

    public int getTableColumnCount() {
        return this.table.getTableModel().getColumnCount();
    }
}

18 Source : CsvUtility.java
with Apache License 2.0
from HongZhaoHua

/**
 * 将对象转换为CSV(TODO 测试发现csv转换为json转换2倍时间)
 *
 * @param instance
 * @return
 */
public static String object2String(Object instance, Type type) {
    StringBuilder buffer = new StringBuilder();
    try (CSVPrinter output = new CSVPrinter(buffer, FORMAT)) {
        writeValue(instance, type, output);
    } catch (Exception exception) {
        throw new RuntimeException(exception);
    }
    return buffer.toString();
}

18 Source : CsvRowCollector.java
with GNU Lesser General Public License v3.0
from FraunhoferIOSB

/**
 * Collects all elements for a single row in a CSV file.
 *
 * First, each element is registered by its header name. This returns the index
 * of the element. After this, for each row, each element is collected in order.
 * If one or more elements are skipped, the elements set to null. Finally, the
 * entire row is flushed to the CSVPrinter, and the collector is reset.
 *
 * @author scf
 */
public clreplaced CsvRowCollector {

    /**
     * The logger for this clreplaced.
     */
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(CsvRowCollector.clreplaced);

    private final CSVPrinter printer;

    private final List<Object> elements = new ArrayList<>();

    private int countTotal = 0;

    private int pointer = 0;

    /**
     * Create a new Collector.
     *
     * @param printer The printer to write the collected elements to.
     */
    public CsvRowCollector(CSVPrinter printer) {
        this.printer = printer;
    }

    /**
     * Register a new element in the collector. The index of the new element is
     * returned. This index must be used when collecting the values of this
     * element.
     *
     * @param headerName The header name of the new element.
     * @return The index of the new element.
     */
    public int registerHeader(String headerName) {
        elements.add(headerName);
        countTotal = elements.size();
        pointer++;
        return countTotal - 1;
    }

    /**
     * Collect a new value for the element with the given index.
     *
     * @param idx The index of the element.
     * @param value The value of the element for the current row.
     */
    public void collectEntry(int idx, Object value) {
        if (idx < pointer) {
            throw new IllegalArgumentException("Elements must be collected in order.");
        }
        while (pointer < idx) {
            elements.set(pointer, null);
            pointer++;
        }
        if (value == null) {
            elements.set(idx, value);
        } else if (value instanceof Collection || value instanceof Map || value instanceof GeoJsonObject || value.getClreplaced().isArray()) {
            try {
                String json = SimpleJsonMapper.getSimpleObjectMapper().writeValuereplacedtring(value);
                elements.set(idx, json);
            } catch (IOException ex) {
                LOGGER.warn("Could not transform collection to JSON.", ex);
                elements.set(idx, value);
            }
        } else {
            elements.set(idx, value);
        }
        pointer++;
    }

    /**
     * Flush the row to the CSVPrinter, and reset the collector.
     *
     * @throws IOException If there is a problem with the printer.
     */
    public void flush() throws IOException {
        while (pointer < countTotal) {
            elements.set(pointer, null);
            pointer++;
        }
        printer.printRecord(elements);
        pointer = 0;
    }
}

18 Source : CommonsCSVPrinterFacade.java
with Apache License 2.0
from apache

/**
 * Wrap <code>CSVPrinter</code> so each print method returns
 * a string to be rendered by FreeMarker instead of writing to an
 * internal writer.
 */
public clreplaced CommonsCSVPrinterFacade implements Flushable, Closeable {

    private final StringWriter writer;

    private final CSVPrinter csvPrinter;

    public CommonsCSVPrinterFacade(CSVFormat format) throws IOException {
        this.writer = new StringWriter();
        this.csvPrinter = new CSVPrinter(writer, format);
    }

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

    @Override
    public void flush() throws IOException {
        csvPrinter.flush();
    }

    public String print(Object value) throws IOException {
        csvPrinter.print(value);
        return getOutput();
    }

    public String printComment(String comment) throws IOException {
        csvPrinter.printComment(comment);
        return getOutput();
    }

    public String println() throws IOException {
        csvPrinter.println();
        return getOutput();
    }

    public String printRecord(Iterable<?> values) throws IOException {
        csvPrinter.printRecord(values);
        return getOutput();
    }

    public String printRecord(Object... values) throws IOException {
        csvPrinter.printRecord(values);
        return getOutput();
    }

    public String printRecords(Iterable<?> values) throws IOException {
        csvPrinter.printRecords(values);
        return getOutput();
    }

    public String printRecords(Object... values) throws IOException {
        csvPrinter.printRecords(values);
        return getOutput();
    }

    public String printRecords(ResultSet resultSet) throws SQLException, IOException {
        csvPrinter.printRecords(resultSet);
        return getOutput();
    }

    private String getOutput() {
        writer.flush();
        final String output = writer.getBuffer().toString();
        writer.getBuffer().setLength(0);
        return output;
    }
}

18 Source : TestDeclarativeSpreadsheetWebScriptGet.java
with GNU Lesser General Public License v3.0
from Alfresco

@Override
protected void populateBody(Object resource, CSVPrinter csv, List<QName> properties) throws IOException {
}

17 Source : CsvUtils.java
with Apache License 2.0
from testingisdocumenting

public static String serialize(Stream<String> header, Stream<List<Object>> rows) {
    try {
        StringWriter out = new StringWriter();
        CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.DEFAULT.withHeader(header.toArray(String[]::new)));
        Iterator<List<Object>> it = rows.iterator();
        while (it.hasNext()) {
            csvPrinter.printRecord(it.next());
        }
        return out.toString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

17 Source : CsvSaver.java
with Apache License 2.0
from nhl

public void save(DataFrame df, Appendable out) {
    try {
        CSVPrinter printer = new CSVPrinter(out, format);
        if (printHeader) {
            printHeader(printer, df.getColumnsIndex());
        }
        int len = df.width();
        for (RowProxy r : df) {
            printRow(printer, r, len);
        }
    } catch (IOException e) {
        throw new RuntimeException("Error writing CSV: " + e.getMessage(), e);
    }
}

17 Source : MapToCsvConverter.java
with MIT License
from mercari

public String line(Object... values) {
    final StringBuilder sb = new StringBuilder();
    try (final CSVPrinter printer = new CSVPrinter(sb, CSVFormat.DEFAULT)) {
        printer.printRecord(values);
        printer.flush();
        return sb.toString().trim();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

17 Source : ColorDataTools.java
with Apache License 2.0
from Mararsh

public static void printHeader(CSVPrinter printer) {
    try {
        if (printer == null) {
            return;
        }
        printer.printRecord("name", "rgba", "rgb", "value", "SRGB", "HSB", "AdobeRGB", "AppleRGB", "EciRGB", "SRGBLinear", "AdobeRGBLinear", "AppleRGBLinear", "CalculatedCMYK", "EciCMYK", "AdobeCMYK", "XYZ", "CieLab", "Lchab", "CieLuv", "Lchuv", "PaletteIndex");
    } catch (Exception e) {
        MyBoxLog.debug(e.toString());
    }
}

17 Source : ColorDataTools.java
with Apache License 2.0
from Mararsh

public static void printRow(CSVPrinter printer, List<String> row, ColorData data) {
    try {
        if (printer == null || row == null || data == null) {
            return;
        }
        row.clear();
        row.add(data.getColorName());
        row.add(data.getRgba());
        row.add(data.getRgb());
        row.add(data.getColorValue() + "");
        row.add(data.getSrgb());
        row.add(data.getHsb());
        row.add(data.getAdobeRGB());
        row.add(data.getAppleRGB());
        row.add(data.getEciRGB());
        row.add(data.getSRGBLinear());
        row.add(data.getAdobeRGBLinear());
        row.add(data.getAppleRGBLinear());
        row.add(data.getCalculatedCMYK());
        row.add(data.getEciCMYK());
        row.add(data.getAdobeCMYK());
        row.add(data.getXyz());
        row.add(data.getCieLab());
        row.add(data.getLchab());
        row.add(data.getCieLuv());
        row.add(data.getLchuv());
        row.add((long) data.getPaletteIndex() + "");
        printer.printRecord(row);
    } catch (Exception e) {
        MyBoxLog.debug(e.toString());
    }
}

17 Source : CsvWriteBackgroundTask.java
with The Unlicense
from Kindrat

@SneakyThrows
private void closePrinter(CSVPrinter printer) {
    printer.close(true);
}

17 Source : AgreementUtils.java
with Apache License 2.0
from inception-project

public static InputStream generateCsvReport(CodingAgreementResult aResult) throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    try (CSVPrinter printer = new CSVPrinter(new OutputStreamWriter(buf, "UTF-8"), CSVFormat.RFC4180)) {
        toCSV(printer, aResult);
    }
    return new ByteArrayInputStream(buf.toByteArray());
}

17 Source : CsvUtility.java
with Apache License 2.0
from HongZhaoHua

private static void writeValue(Object object, Type type, Clreplaced<?> clazz, CsvInformation information, CSVPrinter output) throws IllegalArgumentException, IllegalAccessException, IOException {
    if (object == null) {
        output.print(StringUtility.EMPTY);
        return;
    } else {
        output.print(information.getFields().length);
    }
    // TODO 此处代码需要优化
    HashMap<String, Type> types = new HashMap<>();
    TypeVariable<?>[] typeVariables = clazz.getTypeParameters();
    if (typeVariables.length > 0) {
        ParameterizedType parameterizedType = ParameterizedType.clreplaced.cast(type);
        for (int index = 0; index < typeVariables.length; index++) {
            types.put(typeVariables[index].getName(), parameterizedType.getActualTypeArguments()[index]);
        }
    }
    for (Field field : information.getFields()) {
        Object value = field.get(object);
        type = field.getGenericType();
        if (type instanceof TypeVariable) {
            TypeVariable<?> typeVariable = TypeVariable.clreplaced.cast(type);
            writeValue(value, types.get(typeVariable.getName()), output);
        } else {
            writeValue(value, type, output);
        }
    }
}

17 Source : Table.java
with MIT License
from frictionlessdata

private void writeCSVData(Map<Integer, Integer> mapping, CSVPrinter csvPrinter) {
    try {
        this.iterator(false, false, false, false).forEachRemaining((record) -> {
            String[] sortedRec = new String[record.length];
            for (int i = 0; i < record.length; i++) {
                sortedRec[mapping.get(i)] = (String) record[i];
            }
            try {
                csvPrinter.printRecord(sortedRec);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        });
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

17 Source : ServicesImpl.java
with MIT License
from dharmeshsing

public static void writeCsvFile(File file, String[] header, Collection<?> listToSave) throws Exception {
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(System.lineSeparator()).withQuote('"').withQuoteMode(QuoteMode.ALL);
    try (FileWriter fileWriter = new FileWriter(file);
        CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat)) {
        csvFilePrinter.printRecord(header);
        listToSave.stream().forEach(obj -> {
            if (obj != null) {
                try {
                    if (obj instanceof OrderVO) {
                        csvFilePrinter.printRecord(((OrderVO) obj).getValues());
                    } else {
                        csvFilePrinter.printRecord(((TradeVO) obj).getValues());
                    }
                } catch (Exception e) {
                    throw new RuntimeException("Error writing to file", e);
                }
            }
        });
    }
}

17 Source : CsvDataExportService.java
with GNU Lesser General Public License v3.0
from datageartech

protected void writeDataRecord(CSVPrinter csvPrinter, String[] values) throws IOException {
    for (int i = 0; i < values.length; i++) csvPrinter.print(values[i]);
    csvPrinter.println();
}

17 Source : RmlImplementationReport.java
with MIT License
from carml

public static void main(String[] args) {
    try (FileWriter results = new FileWriter("rml-implementation-report/results.csv");
        FileWriter errors = new FileWriter("rml-implementation-report/errors.csv")) {
        try (CSVPrinter resultPrinter = new CSVPrinter(results, CSVFormat.DEFAULT.withHeader(RESULT_HEADERS));
            CSVPrinter errorPrinter = new CSVPrinter(errors, CSVFormat.DEFAULT.withHeader(ERROR_HEADERS))) {
            populateTestCases().stream().map(RmlImplementationReport::runTestCase).forEach(result -> {
                try {
                    resultPrinter.printRecord(result.getTestCase().getIdentifier(), result.getTestResult());
                    String error = result.getErrorMessage();
                    if (error != null) {
                        errorPrinter.printRecord(result.getTestCase().getIdentifier(), error);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

17 Source : ResultsWriter.java
with GNU Affero General Public License v3.0
from BrightSpots

// add the given candidate(s) names to the csv file next cell
private void addActionRowCandidates(List<String> candidates, CSVPrinter csvPrinter) throws IOException {
    List<String> candidateDisplayNames = new ArrayList<>();
    for (String candidate : candidates) {
        candidateDisplayNames.add(config.getNameForCandidateCode(candidate));
    }
    // use semicolon as delimiter display in a single cell
    String candidateCellText = String.join("; ", candidateDisplayNames);
    csvPrinter.print(candidateCellText);
}

17 Source : UserCSVUploadGet.java
with GNU Lesser General Public License v3.0
from Alfresco

@Override
protected void populateBody(Object resource, CSVPrinter csv, List<QName> properties) throws IOException {
    // Just a blank line is needed
    csv.println();
}

17 Source : TSVWriter.java
with GNU General Public License v3.0
from 20n

// TODO: move this and TSVParser to an replacedysis utility clreplaced.  No reason for them to live deep in package hierarchies.
public clreplaced TSVWriter<K, V> implements AutoCloseable {

    public static final CSVFormat TSV_FORMAT = CSVFormat.newFormat('\t').withRecordSeparator('\n').withQuote('"').withIgnoreEmptyLines(true);

    private List<K> header;

    private CSVPrinter printer;

    public TSVWriter(List<K> header) {
        this.header = header;
    }

    public void open(File f) throws IOException {
        String[] headerStrings = new String[header.size()];
        for (int i = 0; i < header.size(); i++) {
            headerStrings[i] = header.get(i).toString();
        }
        printer = new CSVPrinter(new FileWriter(f), TSV_FORMAT.withHeader(headerStrings));
    }

    public void open(File f, Boolean append) throws IOException {
        if (!append) {
            open(f);
        } else {
            printer = new CSVPrinter(new FileWriter(f, true), TSV_FORMAT);
        }
    }

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

    public void append(Map<K, V> row) throws IOException {
        List<V> vals = new ArrayList<>(header.size());
        for (K field : header) {
            vals.add(row.get(field));
        }
        printer.printRecord(vals);
    }

    public void append(List<Map<K, V>> rows) throws IOException {
        for (Map<K, V> row : rows) {
            append(row);
        }
        printer.flush();
    }

    public void flush() throws IOException {
        printer.flush();
    }
}

16 Source : BoardController.java
with MIT License
from srcclr

@GetMapping(value = "/board/{boardId}/csv", produces = "text/csv")
@Transactional(readOnly = true)
public void getCsv(@PathVariable long boardId, HttpServletResponse response) throws Exception {
    List<TicketCD> result = loadCsvOutput(boardId);
    try (BufferedWriter out = new BufferedWriter(response.getWriter());
        CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT.withHeader(OUTPUT_SUMMARY, OUTPUT_STORY_POINTS, OUTPUT_SPRINT, OUTPUT_EPIC))) {
        for (TicketCD r : result) {
            printer.printRecord(r.getSummary(), r.getPoints(), r.getSprint(), r.getEpic());
        }
    }
}

16 Source : ColorDataTools.java
with Apache License 2.0
from Mararsh

public static void exportCSV(List<ColorData> dataList, File file) {
    try (final CSVPrinter printer = new CSVPrinter(new FileWriter(file, Charset.forName("utf-8")), CSVFormat.DEFAULT)) {
        printHeader(printer);
        List<String> row = new ArrayList<>();
        for (ColorData data : dataList) {
            printRow(printer, row, data);
        }
    } catch (Exception e) {
        MyBoxLog.debug(e.toString());
    }
}

16 Source : RouteLinkInfoWriter.java
with Apache License 2.0
from maestro-performance

/**
 * A router link information writer for AMQP Inspector.
 */
public clreplaced RouteLinkInfoWriter implements InspectorDataWriter<RouterLinkInfo>, AutoCloseable {

    private static final Logger logger = LoggerFactory.getLogger(RouteLinkInfoWriter.clreplaced);

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private BufferedWriter writer;

    private CSVPrinter csvPrinter;

    public RouteLinkInfoWriter(final File logDir, final String name) throws IOException {
        File outputFile = new File(logDir, name + ".csv");
        writer = Files.newBufferedWriter(Paths.get(outputFile.getPath()), Charset.defaultCharset());
        csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Timestamp", "Name", "LinkDir", "OperStatus", "Idenreplacedy", "DeliveryCount", "UndeliveredCount", "PresettledCount", "UnsettledCount", "ReleasedCount", "ModifiedCount", "AcceptedCount", "RejectedCount", "Capacity"));
    }

    /**
     * Close csv printer
     */
    @Override
    public void close() {
        closeQuietly(csvPrinter);
        closeQuietly(writer);
    }

    /**
     * Write single record line into csv file
     * @param now current time
     * @param object one line record
     */
    @SuppressWarnings("unchecked")
    private void write(final LocalDateTime now, final Object object) {
        if (object instanceof Map) {
            final Map<String, Object> routerLinkInfo = (Map<String, Object>) object;
            logger.trace("Router Link information: {}", routerLinkInfo);
            try {
                String timestamp = now.format(formatter);
                csvPrinter.printRecord(timestamp, routerLinkInfo.get("linkName"), routerLinkInfo.get("linkDir"), routerLinkInfo.get("operStatus"), routerLinkInfo.get("idenreplacedy"), routerLinkInfo.get("deliveryCount"), routerLinkInfo.get("undeliveredCount"), routerLinkInfo.get("presettledCount"), routerLinkInfo.get("unsettledCount"), routerLinkInfo.get("releasedCount"), routerLinkInfo.get("modifiedCount"), routerLinkInfo.get("acceptedCount"), routerLinkInfo.get("rejectedCount"), routerLinkInfo.get("capacity"));
            } catch (IOException e) {
                logger.error("Unable to write record: {}", e.getMessage(), e);
            }
        } else {
            logger.warn("Invalid value type for router link");
        }
    }

    /**
     * Write collected data
     * @param now current time
     * @param data data for print
     */
    @SuppressWarnings("unchecked")
    @Override
    public void write(final LocalDateTime now, final RouterLinkInfo data) {
        logger.trace("Router link information: {}", data);
        List<Map<String, Object>> queueProperties = data.getRouterLinkProperties();
        queueProperties.forEach(map -> write(now, map));
    }
}

16 Source : QDMemoryInfoWriter.java
with Apache License 2.0
from maestro-performance

/**
 * A memory information writer for AMQP Inspector.
 */
public clreplaced QDMemoryInfoWriter implements InspectorDataWriter<QDMemoryInfo>, AutoCloseable {

    private static final Logger logger = LoggerFactory.getLogger(ConnectionsInfoWriter.clreplaced);

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private BufferedWriter writer;

    private CSVPrinter csvPrinter;

    public QDMemoryInfoWriter(final File logDir, final String name) throws IOException {
        File outputFile = new File(logDir, name + ".csv");
        writer = Files.newBufferedWriter(Paths.get(outputFile.getPath()), Charset.defaultCharset());
        csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Timestamp", "Name", "Size", "Batch", "Thread-max", "Total", "In-threads", "Rebal-in", "Rebal-out", "totalFreeToHeap", "globalFreeListMax"));
    }

    /**
     * Close csv printer
     */
    @Override
    public void close() {
        closeQuietly(csvPrinter);
        closeQuietly(writer);
    }

    /**
     * Write single record line into csv file
     * @param now current time
     * @param object one line record
     */
    @SuppressWarnings("unchecked")
    private void write(final LocalDateTime now, final Object object) {
        if (object instanceof Map) {
            final Map<String, Object> ConnectionsInfo = (Map<String, Object>) object;
            logger.trace("Memory information: {}", ConnectionsInfo);
            try {
                String timestamp = now.format(formatter);
                csvPrinter.printRecord(timestamp, ConnectionsInfo.get("typeName"), ConnectionsInfo.get("typeSize"), ConnectionsInfo.get("transferBatchSize"), ConnectionsInfo.get("localFreeListMax"), ConnectionsInfo.get("totalAllocFromHeap"), ConnectionsInfo.get("heldByThreads"), ConnectionsInfo.get("batchesRebalancedToThreads"), ConnectionsInfo.get("batchesRebalancedToGlobal"), ConnectionsInfo.get("totalFreeToHeap"), ConnectionsInfo.get("globalFreeListMax"));
            } catch (IOException e) {
                logger.error("Unable to write record: {}", e.getMessage(), e);
            }
        } else {
            logger.warn("Invalid value type for Memory");
        }
    }

    /**
     * Write collected data
     * @param now current time
     * @param data data for print
     */
    @SuppressWarnings("unchecked")
    @Override
    public void write(final LocalDateTime now, final QDMemoryInfo data) {
        logger.trace("Memory information: {}", data);
        List<Map<String, Object>> connectionProperties = data.getQDMemoryInfoProperties();
        connectionProperties.forEach(map -> write(now, map));
    }
}

16 Source : GeneralInfoWriter.java
with Apache License 2.0
from maestro-performance

/**
 * A router link information writer for AMQP Inspector.
 */
public clreplaced GeneralInfoWriter implements InspectorDataWriter<GeneralInfo>, AutoCloseable {

    private static final Logger logger = LoggerFactory.getLogger(GeneralInfoWriter.clreplaced);

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private BufferedWriter writer;

    private CSVPrinter csvPrinter;

    public GeneralInfoWriter(final File logDir, final String name) throws IOException {
        File outputFile = new File(logDir, name + ".csv");
        writer = Files.newBufferedWriter(Paths.get(outputFile.getPath()), Charset.defaultCharset());
        csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Timestamp", "Name", "Version", "Mode", "LinkRoutes", "AutoLinks", "Links", "Nodes", "Addresses", "Connections"));
    }

    /**
     * Close csv printer
     */
    @Override
    public void close() {
        closeQuietly(csvPrinter);
        closeQuietly(writer);
    }

    /**
     * Write single record line into csv file
     * @param now current time
     * @param object one line record
     */
    @SuppressWarnings("unchecked")
    private void write(final LocalDateTime now, final Object object) {
        if (object instanceof Map) {
            final Map<String, Object> routerLinkInfo = (Map<String, Object>) object;
            logger.trace("General information: {}", routerLinkInfo);
            try {
                String timestamp = now.format(formatter);
                csvPrinter.printRecord(timestamp, routerLinkInfo.get("name"), routerLinkInfo.get("version"), routerLinkInfo.get("mode"), routerLinkInfo.get("linkRouteCount"), routerLinkInfo.get("autoLinkCount"), routerLinkInfo.get("linkCount"), routerLinkInfo.get("nodeCount"), routerLinkInfo.get("addrCount"), routerLinkInfo.get("connectionCount"));
            } catch (IOException e) {
                logger.error("Unable to write record: {}", e.getMessage(), e);
            }
        } else {
            logger.warn("Invalid value type for general info");
        }
    }

    /**
     * Write collected data
     * @param now current time
     * @param data data for print
     */
    @SuppressWarnings("unchecked")
    @Override
    public void write(final LocalDateTime now, final GeneralInfo data) {
        logger.trace("Router link information: {}", data);
        List<Map<String, Object>> queueProperties = data.getGeneralProperties();
        queueProperties.forEach(map -> write(now, map));
    }

    @SuppressWarnings("unchecked")
    public void write(InspectorProperties inspectorProperties, final Object object) {
        if (object instanceof GeneralInfo) {
            final Map<String, Object> generalInfo = ((GeneralInfo) object).getGeneralProperties().get(0);
            logger.trace("Router Link information: {}", generalInfo);
            Runtime runtime = Runtime.getRuntime();
            inspectorProperties.setSystemCpuCount(runtime.availableProcessors());
            inspectorProperties.setSystemMemory(runtime.totalMemory());
            inspectorProperties.setOperatingSystemName(System.getProperty("os.name"));
            inspectorProperties.setOperatingSystemArch(System.getProperty("os.arch"));
            inspectorProperties.setOperatingSystemVersion(System.getProperty("os.version"));
            inspectorProperties.setJvmName(System.getProperty("java.vm.name"));
            inspectorProperties.setJvmVersion(System.getProperty("java.specification.version"));
            inspectorProperties.setProductName("Interconnect");
            inspectorProperties.setProductVersion((String) generalInfo.get("version"));
        } else {
            logger.warn("Invalid value type for general info");
        }
    }
}

16 Source : ConnectionsInfoWriter.java
with Apache License 2.0
from maestro-performance

/**
 * A router link information writer for AMQP Inspector.
 */
public clreplaced ConnectionsInfoWriter implements InspectorDataWriter<ConnectionsInfo>, AutoCloseable {

    private static final Logger logger = LoggerFactory.getLogger(ConnectionsInfoWriter.clreplaced);

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private BufferedWriter writer;

    private CSVPrinter csvPrinter;

    public ConnectionsInfoWriter(final File logDir, final String name) throws IOException {
        File outputFile = new File(logDir, name + ".csv");
        writer = Files.newBufferedWriter(Paths.get(outputFile.getPath()), Charset.defaultCharset());
        csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Timestamp", "Container", "Host", "Role", "Dir", "Opened", "Idenreplacedy", "User", "sasl", "Encrypted", "sslProto", "sslCipher", "Tenant", "Authenticated", "Properties"));
    }

    /**
     * Close csv printer
     */
    @Override
    public void close() {
        closeQuietly(csvPrinter);
        closeQuietly(writer);
    }

    /**
     * Write single record line into csv file
     * @param now current time
     * @param object one line record
     */
    @SuppressWarnings("unchecked")
    private void write(final LocalDateTime now, final Object object) {
        if (object instanceof Map) {
            final Map<String, Object> ConnectionsInfo = (Map<String, Object>) object;
            logger.trace("Connections information: {}", ConnectionsInfo);
            try {
                String timestamp = now.format(formatter);
                csvPrinter.printRecord(timestamp, ConnectionsInfo.get("container"), ConnectionsInfo.get("host"), ConnectionsInfo.get("role"), ConnectionsInfo.get("dir"), ConnectionsInfo.get("opened"), ConnectionsInfo.get("idenreplacedy"), ConnectionsInfo.get("user"), ConnectionsInfo.get("sasl"), ConnectionsInfo.get("isEncrypted"), ConnectionsInfo.get("sslProto"), ConnectionsInfo.get("sslCipher"), ConnectionsInfo.get("tenant"), ConnectionsInfo.get("isAuthenticated"), ConnectionsInfo.get("properties"));
            } catch (IOException e) {
                logger.error("Unable to write record: {}", e.getMessage(), e);
            }
        } else {
            logger.warn("Invalid value type for connections");
        }
    }

    /**
     * Write collected data
     * @param now current time
     * @param data data for print
     */
    @SuppressWarnings("unchecked")
    @Override
    public void write(final LocalDateTime now, final ConnectionsInfo data) {
        logger.trace("Connections information: {}", data);
        List<Map<String, Object>> connectionProperties = data.getConnectionProperties();
        connectionProperties.forEach(map -> write(now, map));
    }
}

16 Source : QueueInfoWriter.java
with Apache License 2.0
from maestro-performance

public clreplaced QueueInfoWriter implements InspectorDataWriter<QueueInfo>, AutoCloseable {

    private static final Logger logger = LoggerFactory.getLogger(QueueInfoWriter.clreplaced);

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private BufferedWriter writer;

    private CSVPrinter csvPrinter;

    public QueueInfoWriter(final File logDir, final String name) throws IOException {
        File outputFile = new File(logDir, name + ".csv");
        writer = Files.newBufferedWriter(Paths.get(outputFile.getPath()), Charset.defaultCharset());
        csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Timestamp", "Name", "MessagesAdded", "MessageCount", "MessagesAcknowledged", "MessagesExpired", "ConsumerCount"));
    }

    @Override
    public void close() {
        closeQuietly(csvPrinter);
        closeQuietly(writer);
    }

    private void write(final LocalDateTime now, final String key, final Object object) {
        if (object instanceof Map) {
            final Map<?, ?> queueProperties = (Map<?, ?>) object;
            logger.trace("Queue information: {}", queueProperties);
            try {
                String timestamp = now.format(formatter);
                csvPrinter.printRecord(timestamp, queueProperties.get("Name"), queueProperties.get("MessagesAdded"), queueProperties.get("MessageCount"), queueProperties.get("MessagesAcknowledged"), queueProperties.get("MessagesExpired"), queueProperties.get("ConsumerCount"));
                csvPrinter.flush();
            } catch (IOException e) {
                logger.error("Unable to write record: {}", e.getMessage(), e);
            }
        } else {
            logger.warn("Invalid value type for {}", key);
        }
    }

    @Override
    public void write(final LocalDateTime now, final QueueInfo data) {
        logger.trace("Queue information: {}", data);
        Map<String, Object> queueProperties = data.getQueueProperties();
        queueProperties.forEach((key, value) -> write(now, key, value));
    }
}

16 Source : JVMMemoryInfoWriter.java
with Apache License 2.0
from maestro-performance

public clreplaced JVMMemoryInfoWriter implements InspectorDataWriter<JVMMemoryInfo>, AutoCloseable {

    private static final Logger logger = LoggerFactory.getLogger(JVMMemoryInfoWriter.clreplaced);

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private BufferedWriter writer;

    private CSVPrinter csvPrinter;

    public JVMMemoryInfoWriter(final File logDir, final String name) throws IOException {
        File outputFile = new File(logDir, name + ".csv");
        writer = Files.newBufferedWriter(Paths.get(outputFile.getPath()), Charset.defaultCharset());
        csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("Timestamp", "Name", "Initial", "Max", "Committed", "Used"));
    }

    @Override
    public void close() {
        closeQuietly(csvPrinter);
        closeQuietly(writer);
    }

    @Override
    public void write(final LocalDateTime now, final JVMMemoryInfo data) {
        if (logger.isTraceEnabled()) {
            logger.trace("{} Memory Usage: {}", data.getMemoryAreaName(), data);
        }
        try {
            String timestamp = now.format(formatter);
            csvPrinter.printRecord(timestamp, data.getMemoryAreaName(), data.getInitial(), data.getMax(), data.getCommitted(), data.getUsed());
            csvPrinter.flush();
        } catch (IOException e) {
            logger.error("Unable to write record: {}", e.getMessage(), e);
        }
    }
}

16 Source : CsvWriteBackgroundTask.java
with The Unlicense
from Kindrat

@SneakyThrows
private void printRow(DataObject dataObject, List<String> header, CSVPrinter printer) {
    Object[] fields = header.stream().map(dataObject::get).toArray();
    printer.printRecord(fields);
}

16 Source : Table.java
with MIT License
from frictionlessdata

/**
 * Write as CSV file, the `format` parameter decides on the CSV options. If it is
 * null, then the file will be written as RFC 4180 compliant CSV
 * @param out the Writer to write to
 * @param format the CSV format to use
 * @param sortedHeaders the header row names in the order in which data should be
 *                      exported
 */
// @Override
private void writeCsv(Writer out, CSVFormat format, String[] sortedHeaders) {
    try {
        if (null == sortedHeaders) {
            writeCsv(out, format, getHeaders());
            return;
        }
        CSVFormat locFormat = (null != format) ? format : DataSourceFormat.getDefaultCsvFormat();
        locFormat = locFormat.withHeader(sortedHeaders);
        CSVPrinter csvPrinter = new CSVPrinter(out, locFormat);
        String[] headers = getHeaders();
        Map<Integer, Integer> mapping = TableSchemaUtil.createSchemaHeaderMapping(headers, sortedHeaders);
        writeCSVData(mapping, csvPrinter);
        csvPrinter.close();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

16 Source : ResultsWriter.java
with GNU Affero General Public License v3.0
from BrightSpots

// "action" rows describe which candidates were eliminated or elected
private void addActionRows(CSVPrinter csvPrinter) throws IOException {
    csvPrinter.print("Eliminated");
    for (int round = 1; round <= numRounds; round++) {
        List<String> eliminated = roundToEliminatedCandidates.get(round);
        if (eliminated != null && eliminated.size() > 0) {
            addActionRowCandidates(eliminated, csvPrinter);
        } else {
            csvPrinter.print("");
        }
    }
    csvPrinter.println();
    csvPrinter.print("Elected");
    for (int round = 1; round <= numRounds; round++) {
        List<String> winners = roundToWinningCandidates.get(round);
        if (winners != null && winners.size() > 0) {
            addActionRowCandidates(winners, csvPrinter);
        } else {
            csvPrinter.print("");
        }
    }
    csvPrinter.println();
}

15 Source : CsvFileCreator.java
with Apache License 2.0
from vividus-framework

private void createCsvFile(File directory, CsvFileData csvData, boolean append) throws IOException {
    File file = new File(directory, csvData.getFileName());
    boolean fileExists = file.exists();
    OpenOption[] openOptions = append ? new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.APPEND } : new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING };
    try (Writer writer = new OutputStreamWriter(Files.newOutputStream(file.toPath(), openOptions), StandardCharsets.UTF_8);
        CSVPrinter printer = append && fileExists ? csvFormat.print(writer) : csvFormat.withHeader(csvData.getHeader()).print(writer)) {
        printer.printRecords(csvData.getData());
    }
}

15 Source : OutputExecutor.java
with MIT License
from ssssssss-team

private void releasePrinters() {
    for (Iterator<Map.Entry<String, CSVPrinter>> iterator = this.cachePrinter.entrySet().iterator(); iterator.hasNext(); ) {
        Map.Entry<String, CSVPrinter> entry = iterator.next();
        CSVPrinter printer = entry.getValue();
        if (printer != null) {
            try {
                printer.flush();
                printer.close();
                this.cachePrinter.remove(entry.getKey());
            } catch (IOException e) {
                logger.error("文件输出错误,异常信息:{}", e.getMessage(), e);
                ExceptionUtils.wrapAndThrow(e);
            }
        }
    }
}

15 Source : CsvExporter.java
with Apache License 2.0
from seattle-uat

private void writeHeadersOnFirstExport(CSVPrinter printer) throws IOException {
    if (!wroteHeaders) {
        for (Column column : columns) {
            printer.print(column.header());
        }
        printer.println();
        wroteHeaders = true;
    }
}

15 Source : RDBAccess.java
with MIT License
from RMLio

/**
 * This method creates an CSV-formatted InputStream from a Result Set.
 *
 * @param rs the Result Set that is used.
 * @return a CSV-formatted InputStream.
 * @throws SQLException
 */
private InputStream getCSVInputStream(ResultSet rs) throws SQLException {
    // Get number of requested columns
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    boolean filledInDataTypes = false;
    StringWriter writer = new StringWriter();
    try {
        CSVPrinter printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(getCSVHeader(rsmd, columnCount)));
        printer.printRecords();
        // Extract data from result set
        while (rs.next()) {
            String[] csvRow = new String[columnCount];
            // Iterate over column names
            for (int i = 1; i <= columnCount; i++) {
                String columnName = rsmd.getColumnLabel(i);
                if (!filledInDataTypes) {
                    String dataType = getColumnDataType(rsmd.getColumnTypeName(i));
                    if (dataType != null) {
                        datatypes.put(columnName, dataType);
                    }
                }
                // Add value to CSV row.
                csvRow[i - 1] = rs.getString(columnName);
            }
            // Add CSV row to CSVPrinter.
            // non-varargs call
            printer.printRecord((Object[]) csvRow);
            filledInDataTypes = true;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Get InputStream from StringWriter.
    return new ByteArrayInputStream(writer.toString().getBytes());
}

15 Source : CsvSaver.java
with Apache License 2.0
from nhl

private void printHeader(CSVPrinter printer, Index index) throws IOException {
    for (String label : index.getLabels()) {
        printer.print(label);
    }
    printer.println();
}

15 Source : CsvSaver.java
with Apache License 2.0
from nhl

private void printRow(CSVPrinter printer, RowProxy row, int len) throws IOException {
    for (int i = 0; i < len; i++) {
        printer.print(row.get(i));
    }
    printer.println();
}

15 Source : MapToCsvConverter.java
with MIT License
from mercari

public String lines(List<Map<String, Object>> list, String... names) {
    final StringBuilder sb = new StringBuilder();
    try (final CSVPrinter printer = new CSVPrinter(sb, CSVFormat.DEFAULT)) {
        for (final Map<String, Object> values : list) {
            for (final String name : names) {
                final Object value = getValue(name, values);
                printer.print(value);
            }
            printer.println();
        }
        printer.flush();
        return sb.toString().trim();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

15 Source : DataFileCSVMergeController.java
with Apache License 2.0
from Mararsh

/**
 * @Author Mara
 * @CreateDate 2021-2-13
 * @License Apache License Version 2.0
 */
public clreplaced DataFileCSVMergeController extends FilesMergeController {

    protected CSVFormat sourceFormat, targetFormat;

    protected Charset sourceCharset, targetCharset;

    protected CSVPrinter csvPrinter;

    protected List<String> headers;

    @FXML
    protected ControlCsvOptions csvSourceController, csvTargetController;

    public DataFileCSVMergeController() {
        basereplacedle = AppVariables.message("CsvMerge");
        SourceFileType = VisitHistory.FileType.CSV;
        SourcePathType = VisitHistory.FileType.CSV;
        AddFileType = VisitHistory.FileType.CSV;
        AddPathType = VisitHistory.FileType.CSV;
        TargetPathType = VisitHistory.FileType.CSV;
        TargetFileType = VisitHistory.FileType.CSV;
        sourcePathKey = VisitHistoryTools.getPathKey(VisitHistory.FileType.CSV);
        targetPathKey = VisitHistoryTools.getPathKey(VisitHistory.FileType.CSV);
        sourceExtensionFilter = CommonFxValues.CsvExtensionFilter;
        targetExtensionFilter = CommonFxValues.CsvExtensionFilter;
    }

    @Override
    public void initControls() {
        try {
            super.initControls();
            startButton.disableProperty().unbind();
            startButton.disableProperty().bind(Bindings.isEmpty(tableData).or(Bindings.isEmpty(targetFileInput.textProperty())).or(targetFileInput.styleProperty().isEqualTo(badStyle)).or(csvSourceController.delimiterInput.styleProperty().isEqualTo(badStyle)).or(csvTargetController.delimiterInput.styleProperty().isEqualTo(badStyle)));
        } catch (Exception e) {
            MyBoxLog.error(e.toString());
        }
    }

    @Override
    public void initOptionsSection() {
        try {
            csvSourceController.setControls(baseName + "Source");
            csvTargetController.setControls(baseName + "Target");
        } catch (Exception e) {
            MyBoxLog.error(e.toString());
        }
    }

    @Override
    protected boolean openWriter() {
        try {
            if (csvSourceController.delimiterInput.getStyle().equals(badStyle) || (!csvSourceController.autoDetermine && csvSourceController.charset == null)) {
                return false;
            }
            sourceFormat = CSVFormat.DEFAULT.withDelimiter(csvSourceController.delimiter).withIgnoreEmptyLines().withTrim().withNullString("");
            if (csvSourceController.withNamesCheck.isSelected()) {
                sourceFormat = sourceFormat.withFirstRecordAsHeader();
            }
            sourceCharset = csvSourceController.charset;
            targetFormat = CSVFormat.DEFAULT.withDelimiter(csvTargetController.delimiter).withIgnoreEmptyLines().withTrim().withNullString("");
            if (csvTargetController.withNamesCheck.isSelected()) {
                targetFormat = targetFormat.withFirstRecordAsHeader();
            }
            targetCharset = csvTargetController.charset;
            csvPrinter = new CSVPrinter(new FileWriter(targetFile, targetCharset), targetFormat);
            headers = null;
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public String handleFile(File srcFile) {
        if (csvSourceController.autoDetermine) {
            sourceCharset = FileTools.charset(srcFile);
        }
        String result;
        try (CSVParser parser = CSVParser.parse(srcFile, sourceCharset, sourceFormat)) {
            if (csvTargetController.withNamesCheck.isSelected() && headers == null && csvSourceController.withNamesCheck.isSelected()) {
                headers = new ArrayList<>();
                headers.addAll(parser.getHeaderNames());
                csvPrinter.printRecord(headers);
            }
            List<String> rowData = new ArrayList<>();
            for (CSVRecord record : parser) {
                for (int i = 0; i < record.size(); i++) {
                    rowData.add(record.get(i));
                }
                if (csvTargetController.withNamesCheck.isSelected() && headers == null) {
                    headers = new ArrayList<>();
                    for (int i = 0; i < rowData.size(); i++) {
                        headers.add(message("Field") + i);
                    }
                    csvPrinter.printRecord(headers);
                }
                csvPrinter.printRecord(rowData);
                rowData.clear();
            }
            result = message("Handled") + ": " + srcFile;
        } catch (Exception e) {
            result = srcFile + " " + e.toString();
        }
        return result;
    }

    @Override
    protected boolean closeWriter() {
        try {
            csvPrinter.flush();
            csvPrinter.close();
            try (Connection conn = DriverManager.getConnection(protocol + dbHome() + login)) {
                TableDataDefinition tableDataDefinition = new TableDataDefinition();
                tableDataDefinition.clear(conn, DataDefinition.DataType.DataFile, targetFile.getAbsolutePath());
                conn.commit();
                DataDefinition dataDefinition = DataDefinition.create().setDataName(targetFile.getAbsolutePath()).setDataType(DataDefinition.DataType.DataFile).setCharset(targetCharset.name()).setHasHeader(csvTargetController.withNamesCheck.isSelected()).setDelimiter(csvTargetController.delimiter + "");
                tableDataDefinition.insertData(conn, dataDefinition);
                conn.commit();
            } catch (Exception e) {
                updateLogs(e.toString(), true, true);
                return false;
            }
            return true;
        } catch (Exception e) {
            updateLogs(e.toString(), true, true);
            return false;
        }
    }
}

15 Source : CSVUtils.java
with BSD 3-Clause "New" or "Revised" License
from hxnlyw

/**
 * @return File
 * @Description 创建CSV文件
 * @Param fileName 文件名,head 表头,values 表体
 */
public static File makeTempCSV(String fileName, String[] head, List<String[]> values) throws IOException {
    // 创建文件
    File file = File.createTempFile(fileName, ".csv", new File(PATH.getPath()));
    CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), XmpWriter.UTF8));
    CSVPrinter printer = new CSVPrinter(bufferedWriter, csvFormat);
    // 写入表头
    printer.printRecord(head);
    // 写入内容
    for (String[] value : values) {
        printer.printRecord(value);
    }
    printer.close();
    bufferedWriter.close();
    return file;
}

15 Source : AlignmentSerializer.java
with MIT License
from dwslab

/**
 * Method to write the specified alignment to the specified file (in CSV format).
 * @param alignment The alignment that shall be written.
 * @param file The file to which the alignment shall be written.
 * @throws IOException Exception that occurred while serializing the alignment.
 */
public static void serializeToCSV(Alignment alignment, File file) throws IOException {
    checkFile(file);
    try (CSVPrinter csvPrinter = CSVFormat.DEFAULT.withHeader("source", "target", "confidence", "relation").print(file, StandardCharsets.UTF_8)) {
        for (Correspondence cell : alignment) {
            csvPrinter.printRecord(cell.getEnreplacedyOne(), cell.getEnreplacedyTwo(), cell.getConfidence(), cell.getRelation());
        }
    }
}

15 Source : CsvDataExportService.java
with GNU Lesser General Public License v3.0
from datageartech

protected void writeColumns(CSVPrinter csvPrinter, List<Column> columns) throws DataExchangeException {
    try {
        for (Column column : columns) csvPrinter.print(column.getName());
        csvPrinter.println();
    } catch (IOException e) {
        throw new DataExchangeException(e);
    }
}

15 Source : CSVExporter.java
with MIT License
from ConnectedPlacesCatapult

@Override
public void write(Writer writer, List<Subject> subjects, List<Field> fields, Boolean timeStamp) throws IOException {
    this.timeStamp = null == timeStamp ? true : timeStamp;
    List<String> columnNames = getColumnNames(fields);
    CSVPrinter printer = new CSVPrinter(writer, CSVFormat.DEFAULT);
    printer.printRecord(columnNames);
    for (Subject subject : subjects) {
        printer.printRecord(tabulateSubjectMap(columnNames, flattenSubject(fields, subject)));
    }
}

15 Source : DataSourceService.java
with Apache License 2.0
from BriData

private void writeResultCsv(List<Map<String, String>> csvData, File retFile) throws Exception {
    FileOutputStream fos = null;
    OutputStreamWriter osw = null;
    BufferedWriter bw = null;
    CSVPrinter csvPrinter = null;
    try {
        fos = new FileOutputStream(retFile);
        osw = new OutputStreamWriter(fos);
        bw = new BufferedWriter(osw);
        CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(RETURN_FILE_HEADER);
        csvPrinter = new CSVPrinter(bw, csvFormat);
        for (Map<String, String> map : csvData) {
            List<String> record = new ArrayList<>();
            for (String name : RETURN_FILE_HEADER) {
                record.add(map.get(name));
            }
            csvPrinter.printRecord(record);
        }
        bw.flush();
        fos.flush();
    } finally {
        IOUtils.closeQuietly(bw);
        IOUtils.closeQuietly(osw);
        IOUtils.closeQuietly(fos);
        if (csvPrinter != null)
            csvPrinter.close();
    }
}

15 Source : CSVAppExporter.java
with Apache License 2.0
from Axway-API-Management-Plus

private void writeRecords(CSVPrinter csvPrinter, ClientApplication app, APIAccess apiAccess, QuotaRestriction restriction, Wide wide) throws IOException, AppException {
    switch(wide) {
        case standard:
            writeStandardToCSV(csvPrinter, app);
            break;
        case wide:
            writeWideToCSV(csvPrinter, app, restriction);
            break;
        case ultra:
            writeUltraToCSV(csvPrinter, app, apiAccess);
            break;
        default:
            break;
    }
}

15 Source : CSVAPIExporter.java
with Apache License 2.0
from Axway-API-Management-Plus

private void writeRecords(CSVPrinter csvPrinter, API api, ClientApplication app, Organization org, Wide wide) throws IOException, AppException {
    switch(wide) {
        case standard:
            writeStandardToCSV(csvPrinter, api);
            break;
        case wide:
            writeWideToCSV(csvPrinter, api);
            break;
        case ultra:
            writeAPIUltraToCSV(csvPrinter, api, app, org);
            break;
        default:
            break;
    }
}

See More Examples