Read and Write CSV as String
Updated: Nov 10, 2023
This example shows how to read and write comma-separated values as a single field using the CommaSeparatedValues class.
Java Code Listing
package com.northconcepts.datapipeline.examples.csv; import com.northconcepts.datapipeline.csv.CommaSeparatedValues; public class ReadAndWriteCsvAsString { private static final String[] CONTINENTS = {"Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America"}; public static void main(String[] args) { CommaSeparatedValues commaSeparatedValues = CommaSeparatedValues.fromArray(CONTINENTS); System.out.println(commaSeparatedValues.toCsvString()); commaSeparatedValues.remove(1); System.out.println(commaSeparatedValues.toCsvString()); CommaSeparatedValues csvFromString = CommaSeparatedValues.fromValue(commaSeparatedValues.toCsvString()); System.out.println(csvFromString); System.out.println(csvFromString.subList(2,5).toCsvString()); } }
Code Walkthrough
- An instance of CommaSeparatedValues is created using
.fromArray(CONTINENTS)
which takes in the arrayCONTINENTS
as parameter. .toCsvString()
is used to get aString
and printed to console..remove(1)
is used to remove the value at index 1..toCsvString()
is used again to print the remaining values to console.- Another instance of CommaSeperataValues is created using
.fromValue(commaSeparatedValues.toCsvString())
which takes in aString
as argument. - An overridden
.toString()
method which calls.toCsvString()
is used to print the values to console. .subList(2,5)
is used to get a new instance of CommaSeparatedValues containing only the elements at index 2 to 5..toCsvString()
is then used to print the values to console.