Processes a CSV file.

@param csvFile
the file
@param delimiter
the
@param quoteChar
the quote character ('\0' for no quoting)
@param charset
the character set
@param closure
the {@link Closure} representing a Groovy block
324110
@Cmd
	public void processCsvFile(final String csvFile, final String delimiter, final char quoteChar, final Charset charset,
			final Closure<Void> closure) {
		File f = new File(csvFile);
		try {
			config.extractFromArchive(f, true);
			checkState(f.exists(), "CSV file not found: " + f);
			Reader reader = Files.newReader(f, charset == null ? defaultCharset : charset);
			csvDataProcessor.processFile(reader, delimiter, quoteChar, closure);
		} catch (IOException ex) {
			throw new IllegalStateException("Error reading CSV file: " + f, ex);
		}
	}
5782
private void processFile(InputStream is) throws MPXJException
   {
      int line = 1;

      try
      {
         //
         // Test the header and extract the separator. If this is successful,
         // we reset the stream back as far as we can. The design of the
         // BufferedInputStream class means that we can't get back to character
         // zero, so the first record we will read will get "RMHDR" rather than
         // "ERMHDR" in the first field position.
         //
         BufferedInputStream bis = new BufferedInputStream(is);
         byte[] data = new byte[6];
         data[0] = (byte) bis.read();
         bis.mark(1024);
         bis.read(data, 1, 5);

         if (!new String(data).equals("ERMHDR"))
         {
            throw new MPXJException(MPXJException.INVALID_FILE);
         }

         bis.reset();

         InputStreamReader reader = new InputStreamReader(bis, getCharset());
         Tokenizer tk = new ReaderTokenizer(reader);
         tk.setDelimiter('\t');
         List<String> record = new ArrayList<String>();

         while (tk.getType() != Tokenizer.TT_EOF)
         {
            readRecord(tk, record);
            if (!record.isEmpty())
            {
               if (processRecord(record))
               {
                  break;
               }
            }
            ++line;
         }
      }

      catch (Exception ex)
      {
         throw new MPXJException(MPXJException.READ_ERROR + " (failed at line " + line + ")", ex);
      }
   }
1031422
def csvpretty(csvfile: csvfile=sys.stdin):
    
    shellish.tabulate(csv.reader(csvfile))
141701
@Override
  protected void onNonComplyingFile(File file, String formatted) throws IOException {
    CharSink sink = Files.asCharSink(file, Charsets.UTF_8);
    sink.write(formatted);
  }
439226
@Override
  public boolean tokenizeLine(String line, BufferedReader reader, Record record) throws IOException {
    char separator = separatorChar;
    int len = line.length();
    int start = 0; 
    int j = 0;
    for (int i = 0; i < len; i++) {
      if (line.charAt(i) == separator) {
        put(line, start, i, j, record);
        start = i+1;
        j++;
      }
    }
    put(line, start, len, j, record);
    return true;
  }
59022
public static CsvWriter getWriter(File file, Charset charset, boolean isAppend) {
		return new CsvWriter(file, charset, isAppend);
	}
1156117
def record
      if File.exist? DIFILE
        CSV.open(DIFILE, 'a') { |csv| csv << [@user, @message, @time] }
      else
        CSV.open(DIFILE, 'a') do |csv|
          csv << %w[user message time]
          csv << [@user, @message, @time]
        end
      end
      puts '✓'.green
    rescue StandardError => e
      abort 'Broken'.magenta + e
    end
492208
public void process(String inputFile, String outputFile) throws Exception
   {
      System.out.println("Reading input file started.");
      long start = System.currentTimeMillis();
      ProjectFile projectFile = readFile(inputFile);
      long elapsed = System.currentTimeMillis() - start;
      System.out.println("Reading input file completed in " + elapsed + "ms.");

      System.out.println("Writing output file started.");
      start = System.currentTimeMillis();
      ProjectWriter writer = ProjectWriterUtility.getProjectWriter(outputFile);
      writer.write(projectFile, outputFile);
      elapsed = System.currentTimeMillis() - start;
      System.out.println("Writing output completed in " + elapsed + "ms.");
   }
815467
def validate_csv(file):
    """"""
    try:
        # Detect encoding and dialect
        with file.open() as fp:
            encoding = detect_encoding(fp, default='utf-8')
            sample = fp.read(
                current_app.config.get('PREVIEWER_CSV_VALIDATION_BYTES', 1024))
            delimiter = csv.Sniffer().sniff(sample.decode(encoding)).delimiter
            is_valid = True
    except Exception as e:
        current_app.logger.debug(
            'File {0} is not valid CSV: {1}'.format(file.uri, e))
        encoding = ''
        delimiter = ''
        is_valid = False

    return {
        'delimiter': delimiter,
        'encoding': encoding,
        'is_valid': is_valid
    }
171745
public void toFile(Path outputFile) {
        Validate.notNull(outputFile, "outputFile must not be null");

        applyOverviewDocument().writeToFile(outputFile, StandardCharsets.UTF_8);
        applyPathsDocument().writeToFile(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
        applyDefinitionsDocument().writeToFile(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
        applySecurityDocument().writeToFile(outputFile, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
    }
165981
def is_csv_file(inputfile):
    
    try:
        stream = open(inputfile)
        row = stream.readline()
    except (IOError, UnicodeDecodeError):  # pragma: no cover
        return False
    finally:
        stream.close()
    content = row.strip().split(',')
    return inputfile.endswith('.csv') and len(content) >= 4
367466
static void escape(final Reader reader, final Writer writer) throws IOException {

        if (reader == null) {
            return;
        }

        /*
         * Escape in CSV requires using buffers because CSV escaped text might be surrounded by quotes or not
         * depending on whether they contain any non-alphanumeric chars or not, which is something we cannot
         * know until we find any.
         */

        int doQuote = -1;

        int bufferSize = 0;
        char[] buffer = new char[10];

        int read = reader.read(buffer, 0, buffer.length);
        if (read < 0) {
            return;
        }

        char cq;
        while (doQuote < 0 && read >= 0) {

            int i = bufferSize;
            bufferSize += read;

            while (doQuote < 0 && i < bufferSize) {
                cq = buffer[i++];
                if (!((cq >= 'a' && cq <= 'z') || (cq >= 'A' && cq <= 'Z') || (cq >= '0' && cq <= '9'))) {
                    doQuote = 1; // We must add quotes!
                    break;
                }
            }

            if (doQuote < 0 && read >= 0) {

                if (bufferSize == buffer.length) {
                    // Actually, there is no room for reading more, so let's grow the buffer
                    final char[] newBuffer = new char[buffer.length + (buffer.length / 2)];
                    System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
                    buffer = newBuffer;
                }

                read = reader.read(buffer, bufferSize, (buffer.length - bufferSize));

            }

        }

        doQuote = Math.max(doQuote, 0); // 0 = no quote, 1 = quote


        /*
         * Output initial quotes, if needed
         */
        if (doQuote == 1) {
            writer.write('"');
        }


        /*
         * First we will output the already-checked buffer, escaping quotes as needed
         */
        if (bufferSize > 0) {

            char c;
            for (int i = 0; i < bufferSize; i++) {

                c = buffer[i];

                /*
                 * Check whether the character is a double-quote (in which case, we escape it)
                 */
                if (c == DOUBLE_QUOTE) {
                    writer.write(TWO_DOUBLE_QUOTES);
                } else {
                    writer.write(c);
                }

            }

        }


        /*
         * Once the buffer has been processed, we will process the rest of the input by reading it on-the-fly
         */
        if (read >= 0) {

            int c1, c2; // c1: current char, c2: next char

            c1 = -1;
            c2 = reader.read();

            while (c2 >= 0) {

                c1 = c2;
                c2 = reader.read();

                /*
                 * Check whether the character is a double-quote (in which case, we escape it)
                 */
                if (c1 == DOUBLE_QUOTE) {
                    writer.write(TWO_DOUBLE_QUOTES);
                } else {
                    writer.write(c1);
                }

            }

        }


        /*
         * Output ending quotes, if needed
         */
        if (doQuote == 1) {
            writer.write('"');
        }

    }
1226174
private static void doCopyFile(final File srcFile, final File destFile, final boolean preserveFileDate) {
        if (destFile.exists()) {
            throw new IllegalArgumentException("The destination file already existed: " + destFile.getAbsolutePath());
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel input = null;
        FileChannel output = null;

        try {
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            input = fis.getChannel();
            output = fos.getChannel();

            long size = input.size();
            long pos = 0;
            long count = 0;

            while (pos < size) {
                count = ((size - pos) > FILE_COPY_BUFFER_SIZE) ? FILE_COPY_BUFFER_SIZE : (size - pos);
                pos += output.transferFrom(input, pos, count);
            }
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } finally {
            close(output);
            close(fos);
            close(input);
            close(fis);
        }

        if (srcFile.length() != destFile.length()) {
            deleteAllIfExists(destFile);
            throw new UncheckedIOException(new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"));
        }

        if (preserveFileDate) {
            destFile.setLastModified(srcFile.lastModified());
        }
    }
1220195
public Csv lineDelimiter(String delimiter) {
		Preconditions.checkNotNull(delimiter);
		internalProperties.putString(FORMAT_LINE_DELIMITER, delimiter);
		return this;
	}
31894
public static String[] prepareResponseFile(final File outputFile, final String[] args, final String continuation)
      throws IOException {
    final String baseName = outputFile.getName();
    final File commandFile = new File(outputFile.getParent(), baseName + ".rsp");
    final FileWriter writer = new FileWriter(commandFile);
    for (int i = 1; i < args.length - 1; i++) {
      writer.write(args[i]);
      //
      // if either the current argument ends with
      // or next argument starts with a comma then
      // don't split the line
      if (args[i].endsWith(",") || args[i + 1].startsWith(",")) {
        writer.write(' ');
      } else {
        //
        // split the line to make it more readable
        //
        writer.write(continuation);
      }
    }
    //
    // write the last argument
    //
    if (args.length > 1) {
      writer.write(args[args.length - 1]);
    }
    writer.close();
    final String[] execArgs = new String[2];
    execArgs[0] = args[0];
    //
    // left for the caller to decorate
    execArgs[1] = commandFile.toString();
    return execArgs;
  }
1342513
def convert(input_file_name, **kwargs):
    """"""
    delimiter = kwargs["delimiter"] or ","
    quotechar = kwargs["quotechar"] or "|"

    if six.PY2:
        delimiter = delimiter.encode("utf-8")
        quotechar = quotechar.encode("utf-8")

    # Read CSV and form a header and rows list
    with open(input_file_name, "rb") as input_file:
        reader = csv.reader(input_file,
                            encoding="utf-8",
                            delimiter=delimiter,
                            quotechar=quotechar)

        csv_headers = []
        if not kwargs.get("no_header"):
            # Read header from first line
            csv_headers = next(reader)

        csv_rows = [row for row in reader if row]

        # Set default column name if header is not present
        if not csv_headers and len(csv_rows) > 0:
            end = len(csv_rows[0]) + 1
            csv_headers = ["Column {}".format(n) for n in range(1, end)]

    # Render csv to HTML
    html = render_template(csv_headers, csv_rows, **kwargs)

    # Freeze all JS files in template
    return freeze_js(html)
143244
def output_csv(filehandle: TextIO, values: Iterable[str]) -> None:
    
    line = ",".join(values)
    filehandle.write(line + "\n")