Example usage for org.apache.commons.csv CSVFormat DEFAULT

List of usage examples for org.apache.commons.csv CSVFormat DEFAULT

Introduction

In this page you can find the example usage for org.apache.commons.csv CSVFormat DEFAULT.

Prototype

CSVFormat DEFAULT

To view the source code for org.apache.commons.csv CSVFormat DEFAULT.

Click Source Link

Document

Standard comma separated format, as for #RFC4180 but allowing empty lines.

Usage

From source file:com.compomics.cell_coord.parser.impl.CSVFileParser.java

@Override
public Sample parseTrackFile(File trackFile) throws FileParserException {
    // create a new sample object -- watch out to set the relationships!
    Sample sample = new Sample(trackFile.getName());
    // initialize an empty list of tracks
    List<Track> list = new ArrayList<>();
    CSVParser csvFileParser;//from  w w w . ja v  a 2s .  c o m
    FileReader fileReader;
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(FILE_HEADER_MAPPING);
    try {
        // initialize the file reader
        fileReader = new FileReader(trackFile);
        //initialize CSVParser object
        csvFileParser = new CSVParser(fileReader, csvFileFormat);
        // get the csv records
        List<CSVRecord> csvRecords = csvFileParser.getRecords();
        Track currentTrack = null;
        List<TrackSpot> currentTrackPointList = new ArrayList<>();
        Long currentId = 0L;
        // read the CSV file records starting from the second record to skip the header
        for (int i = 1; i < csvRecords.size(); i++) {
            CSVRecord cSVRecord = csvRecords.get(i);
            // get the fields
            Long trackid = Long.parseLong(cSVRecord.get(TRACK_ID));
            if (!Objects.equals(currentId, trackid)) {
                currentTrack = new Track();
                currentTrack.setTrackid(trackid);
                list.add(currentTrack);
                currentId = trackid;
                currentTrackPointList = new ArrayList<>();
            }
            // create new Track Spot object
            Long spotid = Long.parseLong(cSVRecord.get(SPOT_ID));
            double x = Double.parseDouble(cSVRecord.get(X_COORD));
            double y = Double.parseDouble(cSVRecord.get(Y_COORD));
            double time = Double.parseDouble(cSVRecord.get(TIME));
            TrackSpot trackSpot = new TrackSpot(spotid, x, y, time, currentTrack);
            currentTrackPointList.add(trackSpot);
            currentTrack.setTrackSpots(currentTrackPointList);
            currentTrack.setSample(sample);
        }
    } catch (IOException ex) {
        LOG.error(ex.getMessage(), ex);
    } catch (NumberFormatException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new FileParserException(
                "It seems like a line does not contain a number!\nPlease check your files!");
    }
    // set the tracks for the sample
    sample.setTracks(list);
    return sample;
}

From source file:com.apkcategorychecker.writer.WriterCSV.java

@Override
public void Write(AnalyzerResult result, String _csvPath, int _counter) {

    try {/*from  w ww.  j av a  2s .  co  m*/

        ArrayList<AnalyzerResult> resultList = new ArrayList<AnalyzerResult>();
        resultList.add(result);

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

        CSVFormat format = CSVFormat.DEFAULT.withHeader();

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

        FileWriter _out = new FileWriter(_csvPath, true);
        CSVPrinter printer;
        printer = new CSVPrinter(_out, format.withDelimiter('#'));

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

        Iterator<AnalyzerResult> it = resultList.iterator();
        while (it.hasNext()) {
            AnalyzerResult _resultElement = it.next();
            List<String> resultData = new ArrayList<>();
            resultData.add(String.valueOf(_counter));
            resultData.add(_resultElement.get_APKName());
            resultData.add(_resultElement.get_APKPath());
            resultData.add(_resultElement.get_Package());
            resultData.add(_resultElement.get_APKMainFramework());
            resultData.add(_resultElement.get_APKBaseFramework());
            resultData.add(String.valueOf(_resultElement.get_html()));
            resultData.add(String.valueOf(_resultElement.get_js()));
            resultData.add(String.valueOf(_resultElement.get_css()));
            resultData.add(_resultElement.get_debuggable());
            resultData.add(_resultElement.get_permissions());
            resultData.add(_resultElement.get_minSdkVersion());
            resultData.add(_resultElement.get_maxSdkVersion());
            resultData.add(_resultElement.get_targetSdkVersion());
            resultData.add(_resultElement.get_fileSize());
            resultData.add(String.valueOf(_resultElement.get_startAnalysis()));
            resultData.add(String.valueOf(_resultElement.get_durationAnalysis()));
            resultData.add(String.valueOf(_resultElement.get_decodeSuccess()));
            printer.printRecord(resultData);
        }

        /*--Close the printer--*/
        printer.close();
        System.out.println("Record added to CSV file");
        this.removeBlankLines(_csvPath);

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

}

From source file:geovista.readers.csv.GeogCSVReader_old.java

public Object[] readFileStreaming(InputStream is) {
    // get first line

    BufferedReader in = new BufferedReader(new InputStreamReader(is));
    Iterable<CSVRecord> parser = null;
    try {/*from   w  w  w  . j a  v  a 2 s .  c  o m*/
        parser = CSVFormat.DEFAULT.withDelimiter(this.delimiter).parse(in);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:edu.emory.mathcs.nlp.zzz.CSVRadiology.java

public void categorize(String inputFile) throws Exception {
    CSVParser parser = new CSVParser(IOUtils.createBufferedReader(inputFile), CSVFormat.DEFAULT);
    List<CSVRecord> records = parser.getRecords();
    StringJoiner join;/*w ww.ja  va 2  s .  c  om*/
    CSVRecord record;

    for (int i = 0; i <= 500; i++) {
        if (i == 0)
            continue;
        record = records.get(i);
        join = new StringJoiner(" ");

        for (int j = 2; j < 7; j++)
            join.add(record.get(j));

        System.out.println(join.toString());
    }

    parser.close();
}

From source file:GUI.ReadFile.java

public boolean readTrace(String fileName) {
    FileReader fileReader;//from   w w w  .ja va  2s .  com
    CSVParser csvFileParser;
    boolean isSuccess = true;
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withHeader(TRACE_HEADER_MAPPING);

    try {
        ArrayList<String> Activity_set = new ArrayList<String>();
        HashSet<String> ID_set = new HashSet<String>();
        traces = new ArrayList<Trace>();
        //initialize FileReader object
        System.out.println(fileName);
        fileReader = new FileReader(fileName);

        //initialize CSVParser object
        csvFileParser = new CSVParser(fileReader, csvFileFormat);
        //Get a list of CSV file records
        List<CSVRecord> csvRecords = csvFileParser.getRecords();
        Trace t = new Trace("");
        //Read the CSV file records starting from the second record to skip the header
        for (int i = 1; i < csvRecords.size(); i++) {
            CSVRecord record = csvRecords.get(i);
            String ID = record.get(CaseID);
            if (!ID_set.contains(ID) || (i == csvRecords.size() - 1)) {
                //Discard void trace
                if (i != 1) {
                    traces.add(t);
                }
                ID_set.add(ID);
                t = new Trace(ID);
            }
            Activity ac = new Activity(record.get(Activity), record.get(StartTime), record.get(CompleteTime),
                    record.get(Timestamp));
            t.add_activity(ac);

            if (!Activity_set.contains(ac.get_name())) {
                Activity_set.add(ac.get_name());
            }
        }
        //sort activity set by string
        Collections.sort(Activity_set);

        //sort trace by ID
        Collections.sort(traces, new Comparator<Trace>() {
            @Override
            public int compare(Trace t1, Trace t2) {
                return Integer.parseInt(t1.get_ID()) < Integer.parseInt(t2.get_ID()) ? -1 : 1;
            }
        });
        //Set activity set for each trace
        for (Trace T : traces) {
            T.set_ActivitySet((List<String>) Activity_set.clone());
        }

    } catch (Exception e) {
        System.out.println("Error in CsvFileReader !!!");
        e.printStackTrace();
        isSuccess = false;
        return isSuccess;
    }
    if (isSuccess) {
        try {
            fileReader.close();
            csvFileParser.close();
        } catch (IOException e) {
            System.out.println("Error while closing fileReader/csvFileParser !!!");
        }
    }
    return isSuccess;
}

From source file:com.ibm.watson.app.common.tagEvent.TagRecord.java

public String asCsv() {
    prepareForFormat();/*from  w  ww .  j a  va  2 s .com*/
    StringBuilder sb = new StringBuilder();
    try {
        CSVPrinter printer = new CSVPrinter(sb, CSVFormat.DEFAULT);
        printer.printRecord(this);
        printer.close();
    } catch (IOException e) {

    }
    return sb.toString();

}

From source file:com.streamsets.pipeline.lib.csv.TestCsvParser.java

@Test
public void testParserHeaders() throws Exception {
    CsvParser parser = new CsvParser(getReader("TestCsvParser-default.csv"),
            CSVFormat.DEFAULT.withHeader((String[]) null).withSkipHeaderRecord(true), -1);
    try {//w w  w. j a  va 2  s .  c  om
        Assert.assertArrayEquals(new String[] { "h1", "h2", "h3", "h4" }, parser.getHeaders());
    } finally {
        parser.close();
    }
}

From source file:biz.webgate.dominoext.poi.component.kernel.simpleviewexport.CSVExportProcessor.java

public void process2HTTP(ExportModel expModel, UISimpleViewExport uis, HttpServletResponse hsr,
        DateTimeHelper dth) {// ww w  .  ja v a 2 s  .c  om
    try {
        ByteArrayOutputStream csvBAOS = new ByteArrayOutputStream();
        OutputStreamWriter csvWriter = new OutputStreamWriter(csvBAOS);
        CSVPrinter csvPrinter = new CSVPrinter(csvWriter, CSVFormat.DEFAULT);

        // BUILDING HEADER
        if (uis.isIncludeHeader()) {
            for (ExportColumn expColumn : expModel.getColumns()) {
                csvPrinter.print(expColumn.getColumnName());
            }
            csvPrinter.println();
        }
        // Processing Values
        for (ExportDataRow expRow : expModel.getRows()) {
            for (ExportColumn expColumn : expModel.getColumns()) {
                csvPrinter.print(convertValue(expRow.getValue(expColumn.getPosition()), expColumn, dth));
            }
            csvPrinter.println();
        }
        csvPrinter.flush();

        hsr.setContentType("text/csv");
        hsr.setHeader("Cache-Control", "no-cache");
        hsr.setDateHeader("Expires", -1);
        hsr.setContentLength(csvBAOS.size());
        hsr.addHeader("Content-disposition", "inline; filename=\"" + uis.getDownloadFileName() + "\"");
        OutputStream os = hsr.getOutputStream();
        csvBAOS.writeTo(os);
        os.close();
    } catch (Exception e) {
        ErrorPageBuilder.getInstance().processError(hsr, "Error during SVE-Generation (CSV Export)", e);
    }
}

From source file:ca.uqac.florentinth.speakerauthentication.Dataset.CSVWriter.java

private void openCSVFile(File location) throws IOException {
    fileWriter = new FileWriter(location, true);
    csvPrinter = new CSVPrinter(fileWriter, CSVFormat.DEFAULT.withRecordSeparator(LINE_SEPARATOR));
}

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. c o m
    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();

}