[JAVA-12757] Update code for OpenCSV article

This commit is contained in:
Haroon Khan 2022-07-06 12:00:41 +01:00
parent d90dc9454f
commit f7c39d586e
10 changed files with 212 additions and 253 deletions

View File

@ -1,5 +1,6 @@
package com.baeldung.libraries.opencsv;
import com.baeldung.libraries.opencsv.beans.CsvBean;
import com.baeldung.libraries.opencsv.beans.NamedColumnBean;
import com.baeldung.libraries.opencsv.beans.SimplePositionBean;
import com.baeldung.libraries.opencsv.examples.sync.BeanExamples;
@ -7,102 +8,60 @@ import com.baeldung.libraries.opencsv.examples.sync.CsvReaderExamples;
import com.baeldung.libraries.opencsv.examples.sync.CsvWriterExamples;
import com.baeldung.libraries.opencsv.helpers.Helpers;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class Application {
/*
* Bean Examples.
*/
public static String simpleSyncPositionBeanExample() {
Path path = null;
try {
path = Helpers.twoColumnCsvPath();
} catch (Exception ex) {
Helpers.err(ex);
}
return BeanExamples.beanBuilderExample(path, SimplePositionBean.class).toString();
// CSV Reader Examples
public static List<String[]> readLineByLineSyncExample() throws Exception {
Path path = Helpers.twoColumnCsvPath();
return CsvReaderExamples.readLineByLine(path);
}
public static String namedSyncColumnBeanExample() {
Path path = null;
try {
path = Helpers.namedColumnCsvPath();
} catch (Exception ex) {
Helpers.err(ex);
}
return BeanExamples.beanBuilderExample(path, NamedColumnBean.class).toString();
public static List<String[]> readAllLinesSyncExample() throws Exception {
Path path = Helpers.twoColumnCsvPath();
return CsvReaderExamples.readAllLines(path);
}
public static String writeSyncCsvFromBeanExample() {
Path path = null;
try {
path = Helpers.fileOutBeanPath();
} catch (Exception ex) {
Helpers.err(ex);
}
// CSV Writer Examples
public static String writeLineByLineSyncExample() throws Exception {
Path path = Helpers.fileOutOnePath();
return CsvWriterExamples.writeLineByLine(Helpers.fourColumnCsvString(), path);
}
public static String writeAllLinesSyncExample() throws Exception {
Path path = Helpers.fileOutAllPath();
return CsvWriterExamples.writeAllLines(Helpers.fourColumnCsvString(), path);
}
// Bean Examples
public static List<CsvBean> simpleSyncPositionBeanExample() throws Exception {
Path path = Helpers.twoColumnCsvPath();
return BeanExamples.beanBuilderExample(path, SimplePositionBean.class);
}
public static List<CsvBean> namedSyncColumnBeanExample() throws Exception {
Path path = Helpers.namedColumnCsvPath();
return BeanExamples.beanBuilderExample(path, NamedColumnBean.class);
}
public static String writeSyncCsvFromBeanExample() throws Exception {
Path path = Helpers.fileOutBeanPath();
return BeanExamples.writeCsvFromBean(path);
}
/*
* CSV Reader Examples.
*/
public static String oneByOneSyncExample() {
Reader reader = null;
try {
reader = Files.newBufferedReader(Helpers.twoColumnCsvPath());
} catch (Exception ex) {
Helpers.err(ex);
}
return CsvReaderExamples.oneByOne(reader).toString();
}
public static String readAllSyncExample() {
Reader reader = null;
try {
reader = Files.newBufferedReader(Helpers.twoColumnCsvPath());
} catch (Exception ex) {
Helpers.err(ex);
}
return CsvReaderExamples.readAll(reader).toString();
}
/*
* CSV Writer Examples.
*/
public static String csvWriterSyncOneByOne() {
Path path = null;
try {
path = Helpers.fileOutOnePath();
} catch (Exception ex) {
Helpers.err(ex);
}
return CsvWriterExamples.csvWriterOneByOne(Helpers.fourColumnCsvString(), path);
}
public static String csvWriterSyncAll() {
Path path = null;
try {
path = Helpers.fileOutAllPath();
} catch (Exception ex) {
Helpers.err(ex);
}
return CsvWriterExamples.csvWriterAll(Helpers.fourColumnCsvString(), path);
}
public static void main(String[] args) {
simpleSyncPositionBeanExample();
namedSyncColumnBeanExample();
writeSyncCsvFromBeanExample();
oneByOneSyncExample();
readAllSyncExample();
csvWriterSyncOneByOne();
csvWriterSyncAll();
try {
simpleSyncPositionBeanExample();
namedSyncColumnBeanExample();
writeSyncCsvFromBeanExample();
readLineByLineSyncExample();
readAllLinesSyncExample();
writeLineByLineSyncExample();
writeAllLinesSyncExample();
} catch (Exception e) {
throw new RuntimeException("Error during csv processing", e);
}
}
}

View File

@ -27,5 +27,10 @@ public class NamedColumnBean extends CsvBean {
this.age = age;
}
@Override
public String toString() {
return name + ',' + age;
}
}

View File

@ -26,4 +26,8 @@ public class SimplePositionBean extends CsvBean {
this.exampleColTwo = exampleColTwo;
}
@Override
public String toString() {
return exampleColOne + ',' + exampleColTwo;
}
}

View File

@ -37,4 +37,9 @@ public class WriteExampleBean extends CsvBean {
public void setColC(String colC) {
this.colC = colC;
}
@Override
public String toString() {
return colA + ',' + colB + "," + colC;
}
}

View File

@ -4,60 +4,49 @@ import com.baeldung.libraries.opencsv.beans.CsvBean;
import com.baeldung.libraries.opencsv.beans.WriteExampleBean;
import com.baeldung.libraries.opencsv.helpers.Helpers;
import com.baeldung.libraries.opencsv.pojos.CsvTransfer;
import com.opencsv.CSVWriter;
import com.opencsv.bean.*;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BeanExamples {
public static List<CsvBean> beanBuilderExample(Path path, Class clazz) {
ColumnPositionMappingStrategy ms = new ColumnPositionMappingStrategy();
return beanBuilderExample(path, clazz, ms);
}
public static List<CsvBean> beanBuilderExample(Path path, Class clazz, MappingStrategy ms) {
public static List<CsvBean> beanBuilderExample(Path path, Class<? extends CsvBean> clazz) throws Exception {
CsvTransfer csvTransfer = new CsvTransfer();
try {
ms.setType(clazz);
Reader reader = Files.newBufferedReader(path);
CsvToBean cb = new CsvToBeanBuilder(reader).withType(clazz)
.withMappingStrategy(ms)
.build();
try (Reader reader = Files.newBufferedReader(path)) {
CsvToBean<CsvBean> cb = new CsvToBeanBuilder<CsvBean>(reader)
.withType(clazz)
.build();
csvTransfer.setCsvList(cb.parse());
reader.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return csvTransfer.getCsvList();
}
public static String writeCsvFromBean(Path path) {
try {
Writer writer = new FileWriter(path.toString());
public static String writeCsvFromBean(Path path) throws Exception {
StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer).withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.build();
List<CsvBean> sampleData = Arrays.asList(
new WriteExampleBean("Test1", "sample", "data"),
new WriteExampleBean("Test2", "ipso", "facto")
);
List<CsvBean> list = new ArrayList<>();
list.add(new WriteExampleBean("Test1", "sfdsf", "fdfd"));
list.add(new WriteExampleBean("Test2", "ipso", "facto"));
try (Writer writer = new FileWriter(path.toString())) {
StatefulBeanToCsv<CsvBean> sbc = new StatefulBeanToCsvBuilder<CsvBean>(writer)
.withQuotechar('\'')
.build();
sbc.write(list);
writer.close();
} catch (Exception ex) {
Helpers.err(ex);
sbc.write(sampleData);
}
return Helpers.readFile(path);
}
}

View File

@ -1,61 +1,58 @@
package com.baeldung.libraries.opencsv.examples.sync;
import com.baeldung.libraries.opencsv.helpers.Helpers;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class CsvReaderExamples {
public static List<String[]> readAll(Reader reader) {
public static List<String[]> readAllLines(Path filePath) throws Exception {
CSVParser parser = new CSVParserBuilder()
.withSeparator(',')
.withIgnoreQuotations(true)
.build();
.withSeparator(',')
.withIgnoreQuotations(true)
.build();
CSVReader csvReader = new CSVReaderBuilder(reader)
.withSkipLines(0)
.withCSVParser(parser)
.build();
try (Reader reader = Files.newBufferedReader(filePath)) {
CSVReaderBuilder csvReaderBuilder = new CSVReaderBuilder(reader)
.withSkipLines(0)
.withCSVParser(parser);
List<String[]> list = new ArrayList<>();
try {
list = csvReader.readAll();
reader.close();
csvReader.close();
} catch (Exception ex) {
Helpers.err(ex);
try (CSVReader csvReader = csvReaderBuilder.build()) {
return csvReader.readAll();
}
}
return list;
}
public static List<String[]> oneByOne(Reader reader) {
public static List<String[]> readLineByLine(Path filePath) throws Exception {
List<String[]> list = new ArrayList<>();
try {
CSVParser parser = new CSVParserBuilder()
.withSeparator(',')
.withIgnoreQuotations(true)
.build();
CSVReader csvReader = new CSVReaderBuilder(reader)
.withSkipLines(0)
.withCSVParser(parser)
.build();
CSVParser parser = new CSVParserBuilder()
.withSeparator(',')
.withIgnoreQuotations(true)
.build();
String[] line;
while ((line = csvReader.readNext()) != null) {
list.add(line);
try (Reader reader = Files.newBufferedReader(filePath)) {
CSVReaderBuilder csvReaderBuilder = new CSVReaderBuilder(reader)
.withSkipLines(0)
.withCSVParser(parser);
try (CSVReader csvReader = csvReaderBuilder.build()) {
String[] line;
while ((line = csvReader.readNext()) != null) {
list.add(line);
}
}
reader.close();
csvReader.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return list;
}

View File

@ -9,26 +9,21 @@ import java.util.List;
public class CsvWriterExamples {
public static String csvWriterOneByOne(List<String[]> stringArray, Path path) {
try {
CSVWriter writer = new CSVWriter(new FileWriter(path.toString()));
for (String[] array : stringArray) {
writer.writeNext(array);
public static String writeLineByLine(List<String[]> lines, Path path) throws Exception {
try (CSVWriter writer = new CSVWriter(new FileWriter(path.toString()))) {
for (String[] line : lines) {
writer.writeNext(line);
}
writer.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return Helpers.readFile(path);
}
public static String csvWriterAll(List<String[]> stringArray, Path path) {
try {
CSVWriter writer = new CSVWriter(new FileWriter(path.toString()));
writer.writeAll(stringArray);
writer.close();
} catch (Exception ex) {
Helpers.err(ex);
public static String writeAllLines(List<String[]> lines, Path path) throws Exception {
try (CSVWriter writer = new CSVWriter(new FileWriter(path.toString()))) {
writer.writeAll(lines);
}
return Helpers.readFile(path);
}

View File

@ -1,9 +1,9 @@
package com.baeldung.libraries.opencsv.helpers;
import com.baeldung.libraries.opencsv.Constants;
import org.apache.commons.io.IOUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
@ -13,9 +13,7 @@ import java.util.List;
public class Helpers {
/**
* Write Files
*/
// Write Files
public static Path fileOutAllPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.CSV_All).toURI();
@ -32,9 +30,7 @@ public class Helpers {
return Paths.get(uri);
}
/**
* Read Files
*/
// Read Files
public static Path twoColumnCsvPath() throws URISyntaxException {
URI uri = ClassLoader.getSystemResource(Constants.TWO_COLUMN_CSV).toURI();
@ -51,33 +47,12 @@ public class Helpers {
return Paths.get(uri);
}
/**
* Simple File Reader
*/
public static String readFile(Path path) {
String response = "";
try {
FileReader fr = new FileReader(path.toString());
BufferedReader br = new BufferedReader(fr);
String strLine;
StringBuffer sb = new StringBuffer();
while ((strLine = br.readLine()) != null) {
sb.append(strLine);
}
response = sb.toString();
System.out.println(response);
fr.close();
br.close();
} catch (Exception ex) {
Helpers.err(ex);
}
return response;
public static String readFile(Path path) throws IOException {
return IOUtils.toString(path.toUri());
}
/**
* Dummy Data for Writing.
*/
// Dummy Data for Writing
public static List<String[]> twoColumnCsvString() {
List<String[]> list = new ArrayList<>();
@ -94,15 +69,4 @@ public class Helpers {
return list;
}
/**
* Message Helpers
*/
public static void print(String msg) {
System.out.println(msg);
}
public static void err(Exception ex) {
System.out.println(Constants.GENERIC_EXCEPTION + " " + ex);
}
}

View File

@ -1,5 +1,5 @@
colA, ColB
A, B
C, D
G, G
G, F
colA,colB
A,B
C,D
G,G
G,F
1 colA ColB colB
2 A B B
3 C D D
4 G G G
5 G F F

View File

@ -1,66 +1,107 @@
package com.baeldung.libraries.opencsv;
import com.baeldung.libraries.opencsv.helpers.Helpers;
import org.junit.After;
import org.junit.Before;
import com.baeldung.libraries.opencsv.beans.CsvBean;
import org.junit.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class OpenCsvIntegrationTest {
private Object testReadCsv(Object result) {
assert (result != null);
assert (result instanceof String);
assert (!((String) result).isEmpty());
System.out.println(result);
return result;
}
private static final String NEW_LINE = System.lineSeparator();
private Object testWriteCsv(Object result) {
assert (result instanceof String);
assert (!((String) result).isEmpty());
return result;
}
@Test
public void givenSampleData_whenReadUsingPosition_thenContentsRead() throws Exception {
List<CsvBean> values = Application.simpleSyncPositionBeanExample();
@Before
public void setup() {
assertThat(values)
.extracting(Object::toString)
.containsExactly(
"colA,colB",
"A,B",
"C,D",
"G,G",
"G,F"
);
}
@Test
public void positionExampleTest() {
testReadCsv(Application.simpleSyncPositionBeanExample());
public void givenSampleData_whenReadUsingNamedColumn_thenContentsRead() throws Exception {
List<CsvBean> values = Application.namedSyncColumnBeanExample();
assertThat(values)
.extracting(Object::toString)
.containsExactly(
"Joe,27",
"Jane,32",
"Bob,53"
);
}
@Test
public void namedColumnExampleTest() {
testReadCsv(Application.namedSyncColumnBeanExample());
public void givenSampleData_whenReadLineByLine_thenContentsRead() throws Exception {
List<String[]> lineByLineContents = Application.readLineByLineSyncExample();
assertThat(lineByLineContents)
.containsExactly(
new String[] {"colA", "colB"},
new String[] {"A", "B"},
new String[] {"C", "D"},
new String[] {"G", "G"},
new String[] {"G", "F"}
);
}
@Test
public void writeCsvUsingBeanBuilderTest() {
testWriteCsv(Application.writeSyncCsvFromBeanExample());
public void givenSampleData_whenReadAllLines_thenContentsRead() throws Exception {
List<String[]> contents = Application.readAllLinesSyncExample();
assertThat(contents)
.containsExactly(
new String[] {"colA", "colB"},
new String[] {"A", "B"},
new String[] {"C", "D"},
new String[] {"G", "G"},
new String[] {"G", "F"}
);
}
@Test
public void oneByOneExampleTest() {
testReadCsv(Application.oneByOneSyncExample());
public void givenSampleData_whenWriteCsvUsingBean_thenContentsWritten() throws Exception {
String contents = Application.writeSyncCsvFromBeanExample();
assertThat(contents.split(NEW_LINE))
.containsExactly(
"'colA','colB','colC'",
"'Test1','sample','data'",
"'Test2','ipso','facto'"
);
}
@Test
public void readAllExampleTest() {
testReadCsv(Application.readAllSyncExample());
public void givenSampleData_whenWriteCsvLineByLine_thenContentsWritten() throws Exception {
String contents = Application.writeLineByLineSyncExample();
assertThat(contents.split(NEW_LINE))
.containsExactly(
"\"ColA\",\"ColB\",\"ColC\",\"ColD\"",
"\"A\",\"B\",\"A\",\"B\"",
"\"BB\",\"AB\",\"AA\",\"B\""
);
}
@Test
public void csvWriterOneByOneTest() {
testWriteCsv(Application.csvWriterSyncOneByOne());
public void givenSampleData_whenWriteCsvAllLines_thenContentsWritten() throws Exception {
String contents = Application.writeAllLinesSyncExample();
assertThat(contents.split(NEW_LINE))
.containsExactly(
"\"ColA\",\"ColB\",\"ColC\",\"ColD\"",
"\"A\",\"B\",\"A\",\"B\"",
"\"BB\",\"AB\",\"AA\",\"B\""
);
}
@Test
public void csvWriterAllTest() {
testWriteCsv(Application.csvWriterSyncAll());
}
@After
public void close() {
}
}