Return to extract the column string from a row string of CSV - Java java.io

Java examples for java.io:File CSV

Introduction

Write code to Return to extract the column string from a row string of CSV.

Is divided by a comma string and returns a string of the specified column.

The first column begins with 0 .

If the column does not exist is specified, null is returned.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String line = "java2s.com";
        int col = 42;
        System.out.println(getCsvData(line, col));
    }// w  w  w .j av a  2s .c o m

    /** Empty string */
    public static final String EMPTY = "";
    /** CSV delimiter */
    public static final String CSV_DELIMITER = ",";

    /**
     * Return to extract the column string from a row string of CSV.<br/>
     * Is divided by a comma string and returns a string of the specified
     * column.<br/>
     * The first column begins with {@code 0}.<br/>
     * If the column does not exist is specified, null is returned.<br/>
     * 
     * @param line
     *            String that contains a comma in CSV
     * @param col
     *            Column number to retrieve
     * @return The return of the CSV data of the specified column
     */
    public static String getCsvData(String line, int col) {
        String[] csvDatas = line.split(CSV_DELIMITER);
        if (csvDatas.length > col) {
            return csvDatas[col];
        }
        return EMPTY;
    }
}

Related Tutorials