Example usage for org.apache.commons.csv CSVPrinter close

List of usage examples for org.apache.commons.csv CSVPrinter close

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVPrinter close.

Prototype

@Override
    public void close() throws IOException 

Source Link

Usage

From source file:ca.twoducks.vor.ossindex.report.Assistant.java

/** Export the configuration data into a CSV file. The CSV file may not
 * contain complete information, but is much easier for a human to work with.
 * Code will be added to allow conversion from CSV back into the JSON format.
 * /*w  w  w . j  a va2s .co  m*/
 * @param dir
 * @throws IOException 
 */
private void exportCsv(File dir) throws IOException {
    File file = new File(dir, "vorindex.csv");
    CSVFormat format = CSVFormat.EXCEL.withRecordSeparator("\n").withCommentMarker('#');
    FileWriter fout = new FileWriter(file);
    CSVPrinter csvOut = new CSVPrinter(fout, format);
    String[] header = { "Path", "State", "Project Name", "Project URI", "Version", "CPEs", "Project Licenses",
            "File License", "Project Description", "Digest", "Comment" };
    csvOut.printRecord((Object[]) header);

    try {
        config.exportCsv(csvOut, includeArtifacts, includeImages);
    } finally {
        fout.close();
        csvOut.close();
    }

}

From source file:com.apkcategorychecker.json.DefaultJsCSVBuilder.java

@Override
public void BuildJs(ArrayList<JsElement> jsList, String _destinationPath, String time) {

    try {//w  ww .j a  v a2 s. c  o m

        /*Check if _destinationPath is an APK or a Directory in order to
        *get the right destination path
        */

        File Destination = new File(_destinationPath);
        if (!Destination.exists()) {
            Destination.mkdir();
        }
        if (Destination.isDirectory()) {
            this._destPath = _destinationPath;
        } else if (Destination.isFile()) {
            this._destPath = _destinationPath.substring(0, _destinationPath.length() - 4);
        }

        /*--Create the CSVFormat object--*/

        CSVFormat format = CSVFormat.EXCEL.withHeader().withDelimiter(',');

        /*--Writing in a CSV file--*/

        File _fileCSV = new File(_destPath + "/Results-JS FILES_" + time + ".csv");
        FileWriter _out = new FileWriter(_fileCSV);
        CSVPrinter printer;
        printer = new CSVPrinter(_out, format.withDelimiter('#'));
        System.out.println("Creating " + "Results-JS FILES_" + time + ".csv ....");
        try {
            printer.printRecord("appID", "jsFiles");
        } catch (IOException ex) {
            Logger.getLogger(WriterCSV.class.getName()).log(Level.SEVERE, null, ex);
        }

        /*--Retrieve APKResult and Write in file--*/

        @SuppressWarnings("unused")
        int i = 0;
        Iterator<JsElement> it = jsList.iterator();
        while (it.hasNext()) {
            JsElement _resultElement = it.next();
            List<String> resultData = new ArrayList<>();
            resultData.add(_resultElement.get_Id());
            resultData.add(_resultElement.get_JsFiles());
            i++;
            printer.printRecord(resultData);
        }

        /*--Close the printer--*/
        printer.close();
        System.out.println("Results-JS FILES_" + time + ".csv created");

    } catch (IOException ex) {
        Logger.getLogger(WriterCSV.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.team3637.service.ScheduleServiceMySQLImpl.java

@Override
public void exportCSV(String outputFile) {
    List<Schedule> data = getSchedule();
    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;
    try {/*  www .  j a v a  2  s  . c om*/
        fileWriter = new FileWriter(outputFile);
        csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator("\n"));
        for (int i = 0; i < data.size(); i++) {
            List<Object> line = new ArrayList<>();
            for (Field field : Schedule.class.getDeclaredFields()) {
                field.setAccessible(true);
                Object value = field.get(data.get(i));
                line.add(value);
            }
            csvFilePrinter.printRecord(line);
        }
    } catch (IOException | IllegalAccessException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileWriter != null) {
                fileWriter.flush();
                fileWriter.close();
            }
            if (csvFilePrinter != null) {
                csvFilePrinter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.blackducksoftware.integration.hubdiff.HubDiff.java

public String writeDiffAsCSV(File file) throws IOException {
    if (!file.exists()) {
        file.createNewFile();//from  w  w  w . j a  v a 2  s .  c  o  m
    }

    CSVPrinter printer = new CSVPrinter(new PrintStream(file), CSVFormat.EXCEL);

    printer.printRecord("HubVersions", swaggerDoc1.getVersion(), " -> ", swaggerDoc2.getVersion());
    printer.printRecord("Operation", "Expected", "Actual", "Field");

    // Log all additions to the API
    for (FieldComparisonFailure added : results.getFieldUnexpected()) {
        printer.printRecord("ADDED", added.getExpected(), added.getActual(), added.getField());
    }
    // Log all changes made to the API
    for (FieldComparisonFailure changed : results.getFieldFailures()) {
        printer.printRecord("CHANGED", changed.getExpected(), changed.getActual(), changed.getField());
    }
    // Log all deletions made to the API
    for (FieldComparisonFailure removed : results.getFieldMissing()) {
        printer.printRecord("REMOVED", removed.getExpected(), removed.getActual(), removed.getField());
    }

    printer.close();
    return FileUtils.readFileToString(file, StandardCharsets.UTF_8);
}

From source file:mekhq.Utilities.java

/**
 * Export a JTable to a CSV file// w  w  w . j  av  a 2 s  .  c om
 * @param table
 * @param file
 * @return report
 */
public static String exportTabletoCSV(JTable table, File file) {
    String report;
    try {
        TableModel model = table.getModel();
        BufferedWriter writer = Files.newBufferedWriter(Paths.get(file.getPath()));
        String[] columns = new String[model.getColumnCount()];
        for (int i = 0; i < model.getColumnCount(); i++) {
            columns[i] = model.getColumnName(i);
        }
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader(columns));

        for (int i = 0; i < model.getRowCount(); i++) {
            Object[] towrite = new String[model.getColumnCount()];
            for (int j = 0; j < model.getColumnCount(); j++) {
                // use regex to remove any HTML tags
                towrite[j] = model.getValueAt(i, j).toString().replaceAll("\\<[^>]*>", "");
            }
            csvPrinter.printRecord(towrite);
        }

        csvPrinter.flush();
        csvPrinter.close();

        report = model.getRowCount() + " " + resourceMap.getString("RowsWritten.text");
    } catch (Exception ioe) {
        MekHQ.getLogger().log(Utilities.class, "exportTabletoCSV", LogLevel.INFO, "Error exporting JTable");
        report = "Error exporting JTable. See log for details.";
    }
    return report;
}

From source file:com.team3637.service.TeamServiceMySQLImpl.java

@Override
public void exportCSV(String outputFile) {
    List<Team> data = getTeams();
    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;
    try {/*from ww  w  .j a  v  a2s.  c o m*/
        fileWriter = new FileWriter(outputFile);
        csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator("\n"));
        for (Team team : data) {
            List<Object> line = new ArrayList<>();
            for (Field field : Team.class.getDeclaredFields()) {
                field.setAccessible(true);
                Object value = field.get(team);
                line.add(value);
            }
            csvFilePrinter.printRecord(line);
        }
    } catch (IOException | IllegalAccessException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileWriter != null) {
                fileWriter.flush();
                fileWriter.close();
            }
            if (csvFilePrinter != null) {
                csvFilePrinter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:be.roots.taconic.pricingguide.service.ReportServiceImpl.java

@Override
public void report(Contact contact, List<String> modelIds) throws IOException {

    final CSVFormat csvFileFormat = CSVFormat.DEFAULT;
    final FileWriter fileWriter = new FileWriter(getFileNameFor(new DateTime()), true);
    final CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);

    final List<String> record = new ArrayList<>();

    record.add(new DateTime().toString(DefaultUtil.FORMAT_TIMESTAMP));

    record.add(contact.getHsId());/*from  w w  w.j a  v  a 2 s  . com*/
    record.add(contact.getSalutation());
    record.add(contact.getFirstName());
    record.add(contact.getLastName());
    record.add(contact.getEmail());
    record.add(contact.getCompany());
    record.add(contact.getCountry());
    record.add(contact.getPersona());
    if (contact.getJobRole() != null) {
        record.add(contact.getJobRole().getDescription());
    } else {
        record.add(null);
    }
    if (contact.getCurrency() != null) {
        record.add(contact.getCurrency().name());
        record.add(contact.getCurrency().getDescription());
    } else {
        record.add(null);
        record.add(null);
    }

    record.addAll(modelIds);

    csvFilePrinter.printRecord(record);
    csvFilePrinter.close();

}

From source file:com.team3637.service.MatchServiceMySQLImpl.java

@Override
public void exportCSV(String outputFile) {
    List<Match> data = getMatches();
    FileWriter fileWriter = null;
    CSVPrinter csvFilePrinter = null;
    try {//  www. j  ava2s .  com
        fileWriter = new FileWriter(outputFile);
        csvFilePrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator("\n"));
        for (Match match : data) {
            List<Object> line = new ArrayList<>();
            for (Field field : Match.class.getDeclaredFields()) {
                field.setAccessible(true);
                Object value = field.get(match);
                line.add(value);
            }
            csvFilePrinter.printRecord(line);
        }
    } catch (IOException | IllegalAccessException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileWriter != null) {
                fileWriter.flush();
                fileWriter.close();
            }
            if (csvFilePrinter != null) {
                csvFilePrinter.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:mekhq.campaign.finances.Finances.java

public String exportFinances(String path, String format) {
    String report;//  ww  w .  j ava  2  s.com

    try {
        BufferedWriter writer = Files.newBufferedWriter(Paths.get(path));
        CSVPrinter csvPrinter = new CSVPrinter(writer,
                CSVFormat.DEFAULT.withHeader("Date", "Category", "Description", "Amount", "RunningTotal"));
        SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");

        int running_total = 0;
        for (int i = 0; i < transactions.size(); i++) {
            running_total += transactions.get(i).getAmount();
            csvPrinter.printRecord(df.format(transactions.get(i).getDate()),
                    transactions.get(i).getCategoryName(), transactions.get(i).getDescription(),
                    transactions.get(i).getAmount(), running_total);
        }

        csvPrinter.flush();
        csvPrinter.close();

        report = transactions.size() + " " + resourceMap.getString("FinanceExport.text");
    } catch (IOException ioe) {
        MekHQ.getLogger().log(getClass(), "exportFinances", LogLevel.INFO,
                "Error exporting finances to " + format);
        report = "Error exporting finances. See log for details.";
    }

    return report;
}

From source file:com.itemanalysis.psychometrics.irt.estimation.ItemResponseSimulator.java

/**
 * Generates a comma separated file (CSV file) of item responses.
 *
 * @param outputFile complete path and file name of output file
 * @param includeID include an examinee ID number in the first column if true. Omits the ID if false.
 * @param includeHeader if true will include variable names in first row of CSV file.
 * @throws IOException//w  w w.ja v a 2  s.com
 */
public void generateData(String outputFile, boolean includeID, boolean includeHeader) throws IOException {
    byte[][] x = generateData();
    int baseID = nPeople * 10 + 1;

    Writer writer = null;
    CSVPrinter printer = null;
    File file = new File(outputFile);

    try {
        writer = new OutputStreamWriter(new FileOutputStream(file));
        printer = new CSVPrinter(writer, CSVFormat.DEFAULT.withCommentMarker('#'));

        if (includeHeader) {
            if (includeID)
                printer.print("ID");
            for (int j = 0; j < nItems; j++) {
                printer.print("V" + (j + 1));
            }
            printer.println();
        }

        for (int i = 0; i < nPeople; i++) {
            if (includeID)
                printer.print(baseID);
            for (int j = 0; j < nItems; j++) {
                printer.print(x[i][j]);
            }
            printer.println();
            baseID++;
        }
    } catch (IOException ex) {
        throw (ex);
    } finally {
        if (writer != null)
            writer.close();
        if (printer != null)
            printer.close();
    }

}