public synchronized EnrichmentResultWriter open() { LOG.info("Opening result writer on file: " + outFile.getAbsolutePath()); if (outFile.exists()) { throw new RuntimeException("File already exists, stopping: " + outFile.getAbsolutePath()); } checkIfWritable(outFile); final FileWriter fileWriter; try { fileWriter = new FileWriter(outFile, true); } catch (IOException e) { throw new RuntimeException(e); } try { this.printer = new CSVPrinter( fileWriter, CSVFormat.EXCEL .withDelimiter(';') .withHeader("idRef", "isbn", "userEmail", "resultStatus", "errorMessage")); } catch (IOException e) { throw new RuntimeException("Unable to write results to CSV: " + outFile.getAbsolutePath(), e); } return this; }
/** * Returns a <code>CSVParser</code> object to access the contents of an open file, possibly * without a header row and a different data delimiter than a comma. * * <p>Each line of the file should be formatted as data separated by the delimiter passed as a * parameter and with/without a header row to describe the column names. This is useful if the * data is separated by some character other than a comma. * * @param withHeader uses first row of data as a header row only if true * @param delimiter a single character that separates one field of data from another * @return a <code>CSVParser</code> that can provide access to the records in the file one at a * time * @throws exception if this file does not represent a CSV formatted data * @throws exception if <code>delimiter.length() != 1</code> */ public CSVParser getCSVParser(boolean withHeader, String delimiter) { if (delimiter == null || delimiter.length() != 1) { throw new ResourceException( "FileResource: CSV delimiter must be a single character: " + delimiter); } try { char delim = delimiter.charAt(0); Reader input = new StringReader(mySource); if (withHeader) { return new CSVParser(input, CSVFormat.EXCEL.withHeader().withDelimiter(delim)); } else { return new CSVParser(input, CSVFormat.EXCEL.withDelimiter(delim)); } } catch (Exception e) { throw new ResourceException("FileResource: cannot read " + myPath + " as a CSV file."); } }