JAVA-2105: Move articles out of core-java-io module
This commit is contained in:
@@ -6,4 +6,6 @@ This module contains articles about core Java input/output(IO) conversions.
|
||||
- [Java InputStream to String](https://www.baeldung.com/convert-input-stream-to-string)
|
||||
- [Java – Write an InputStream to a File](https://www.baeldung.com/convert-input-stream-to-a-file)
|
||||
- [Converting a BufferedReader to a JSONObject](https://www.baeldung.com/java-bufferedreader-to-jsonobject)
|
||||
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
|
||||
- [How to Write to a CSV File in Java](https://www.baeldung.com/java-csv)
|
||||
- More articles: [[<-- prev]](/core-java-modules/core-java-io-conversions)
|
||||
|
||||
@@ -26,6 +26,12 @@
|
||||
<artifactId>json</artifactId>
|
||||
<version>${json.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.opencsv</groupId>
|
||||
<artifactId>opencsv</artifactId>
|
||||
<version>${opencsv.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -40,6 +46,7 @@
|
||||
|
||||
<properties>
|
||||
<json.version>20200518</json.version>
|
||||
<opencsv.version>4.1</opencsv.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.csv;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class WriteCsvFileExample {
|
||||
|
||||
public String convertToCSV(String[] data) {
|
||||
return Stream.of(data)
|
||||
.map(this::escapeSpecialCharacters)
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
public String escapeSpecialCharacters(String data) {
|
||||
String escapedData = data.replaceAll("\\R", " ");
|
||||
if (data.contains(",") || data.contains("\"") || data.contains("'")) {
|
||||
data = data.replace("\"", "\"\"");
|
||||
escapedData = "\"" + data + "\"";
|
||||
}
|
||||
return escapedData;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package com.baeldung.csv;
|
||||
|
||||
import com.opencsv.CSVReader;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
|
||||
public class ReadCSVInArrayUnitTest {
|
||||
public static final String COMMA_DELIMITER = ",";
|
||||
public static final String CSV_FILE = "src/test/resources/book.csv";
|
||||
public static final List<List<String>> EXPECTED_ARRAY = Collections.unmodifiableList(new ArrayList<List<String>>() {
|
||||
{
|
||||
add(new ArrayList<String>() {
|
||||
{
|
||||
add("Mary Kom");
|
||||
add("Unbreakable");
|
||||
}
|
||||
});
|
||||
add(new ArrayList<String>() {
|
||||
{
|
||||
add("Kapil Isapuari");
|
||||
add("Farishta");
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@Test
|
||||
public void givenCSVFile_whenBufferedReader_thenContentsAsExpected() throws IOException {
|
||||
List<List<String>> records = new ArrayList<List<String>>();
|
||||
try (BufferedReader br = new BufferedReader(new FileReader(CSV_FILE))) {
|
||||
String line = "";
|
||||
while ((line = br.readLine()) != null) {
|
||||
String[] values = line.split(COMMA_DELIMITER);
|
||||
records.add(Arrays.asList(values));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
|
||||
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
|
||||
.toArray(),
|
||||
records.get(i)
|
||||
.toArray());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCSVFile_whenScanner_thenContentsAsExpected() throws IOException {
|
||||
List<List<String>> records = new ArrayList<List<String>>();
|
||||
try (Scanner scanner = new Scanner(new File(CSV_FILE));) {
|
||||
while (scanner.hasNextLine()) {
|
||||
records.add(getRecordFromLine(scanner.nextLine()));
|
||||
}
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
|
||||
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
|
||||
.toArray(),
|
||||
records.get(i)
|
||||
.toArray());
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> getRecordFromLine(String line) {
|
||||
List<String> values = new ArrayList<String>();
|
||||
try (Scanner rowScanner = new Scanner(line)) {
|
||||
rowScanner.useDelimiter(COMMA_DELIMITER);
|
||||
while (rowScanner.hasNext()) {
|
||||
values.add(rowScanner.next());
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCSVFile_whenOpencsv_thenContentsAsExpected() throws IOException {
|
||||
List<List<String>> records = new ArrayList<List<String>>();
|
||||
try (CSVReader csvReader = new CSVReader(new FileReader(CSV_FILE));) {
|
||||
String[] values = null;
|
||||
while ((values = csvReader.readNext()) != null) {
|
||||
records.add(Arrays.asList(values));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
for (int i = 0; i < EXPECTED_ARRAY.size(); i++) {
|
||||
Assert.assertArrayEquals(EXPECTED_ARRAY.get(i)
|
||||
.toArray(),
|
||||
records.get(i)
|
||||
.toArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.baeldung.csv;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class WriteCsvFileExampleUnitTest {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WriteCsvFileExampleUnitTest.class);
|
||||
|
||||
private WriteCsvFileExample csvExample;
|
||||
|
||||
@Before
|
||||
public void setupClass() {
|
||||
csvExample = new WriteCsvFileExample();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCommaContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() {
|
||||
String data = "three,two,one";
|
||||
String escapedData = csvExample.escapeSpecialCharacters(data);
|
||||
|
||||
String expectedData = "\"three,two,one\"";
|
||||
assertEquals(expectedData, escapedData);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenQuoteContainingData_whenEscapeSpecialCharacters_stringReturnedFormatted() {
|
||||
String data = "She said \"Hello\"";
|
||||
String escapedData = csvExample.escapeSpecialCharacters(data);
|
||||
|
||||
String expectedData = "\"She said \"\"Hello\"\"\"";
|
||||
assertEquals(expectedData, escapedData);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNewlineContainingData_whenEscapeSpecialCharacters_stringReturnedInQuotes() {
|
||||
String dataNewline = "This contains\na newline";
|
||||
String dataCarriageReturn = "This contains\r\na newline and carriage return";
|
||||
String escapedDataNl = csvExample.escapeSpecialCharacters(dataNewline);
|
||||
String escapedDataCr = csvExample.escapeSpecialCharacters(dataCarriageReturn);
|
||||
|
||||
String expectedData = "This contains a newline";
|
||||
assertEquals(expectedData, escapedDataNl);
|
||||
String expectedDataCr = "This contains a newline and carriage return";
|
||||
assertEquals(expectedDataCr, escapedDataCr);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonSpecialData_whenEscapeSpecialCharacters_stringReturnedUnchanged() {
|
||||
String data = "This is nothing special";
|
||||
String returnedData = csvExample.escapeSpecialCharacters(data);
|
||||
|
||||
assertEquals(data, returnedData);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDataArray_whenConvertToCSV_thenOutputCreated() throws IOException {
|
||||
List<String[]> dataLines = new ArrayList<String[]>();
|
||||
dataLines.add(new String[] { "John", "Doe", "38", "Comment Data\nAnother line of comment data" });
|
||||
dataLines.add(new String[] { "Jane", "Doe, Jr.", "19", "She said \"I'm being quoted\"" });
|
||||
|
||||
File csvOutputFile = File.createTempFile("exampleOutput", ".csv");
|
||||
try (PrintWriter pw = new PrintWriter(csvOutputFile)) {
|
||||
dataLines.stream()
|
||||
.map(csvExample::convertToCSV)
|
||||
.forEach(pw::println);
|
||||
} catch (FileNotFoundException e) {
|
||||
LOG.error("IOException " + e.getMessage());
|
||||
}
|
||||
|
||||
assertTrue(csvOutputFile.exists());
|
||||
csvOutputFile.deleteOnExit();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
Mary Kom,Unbreakable
|
||||
Kapil Isapuari,Farishta
|
||||
|
Reference in New Issue
Block a user