When reading or writing CSV files in Java, you can use a library called OpenCsv. Of course, if you create a simple CSV file, you can implement it yourself.
Since I was only going to create a simple CSV file, I only implemented a read/write method. If you go to the site and look at the examples, we will guide you through creating efficient CSV files in an advanced way.
If you want to use the advanced features of OpenCsv, it would be good to refer to OpenCsv.
library settings
I have created a project with Gradle. If you use gradle, you can set the dependency as follows.
dependencies {
...
implementation group: 'com.opencsv', name: 'opencsv', version: '4.4'
}
Write CSV
The following example creates a CSV file.
package example;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class OpenCsv {
public static void writeDataToCsv(String filePath) throws IOException {
CSVWriter writer = new CSVWriter(new FileWriter(filePath));
String[] entries = "EW#City#State".split("#"); // 1
writer.writeNext(entries); // 2
String[] entries1 = {"W", "Youngstown", "OH"}; // 3
writer.writeNext(entries1);
String[] entries2 = {"W", "Williamson", "WV"};
writer.writeNext(entries2);
writer.close();
}
public static void main(String args[]) throws IOException {
writeDataToCsv("./sample.csv");
}
}
- You can create an array of strings using
split()
. - When
writeNext()
is called, the argument is saved in the CSV file. - You can also directly put items into the array.
The contents of the generated file are as follows.
"EW","City","State"
"W","Youngstown","OH"
"W","Williamson","WV"
Read CSV
The following is an example of creating a CSV file, reading the CSV file, and outputting data.
package example;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class OpenCsv {
public static void writeDataToCsv(String filePath) throws IOException {
CSVWriter writer = new CSVWriter(new FileWriter(filePath));
String[] entries = "EW#City#State".split("#"); // 1
writer.writeNext(entries);
String[] entries1 = {"W", "Youngstown", "OH"}; // 2
writer.writeNext(entries1);
String[] entries2 = {"W", "Williamson", "WV"};
writer.writeNext(entries2);
writer.close();
}
public static void readDataFromCsv(String filePath) throws IOException {
CSVReader reader = new CSVReader(new FileReader(filePath)); // 1
String [] nextLine;
while ((nextLine = reader.readNext()) != null) { // 2
for (int i = 0; i < nextLine.length; i++) {
System.out.println(i + " " + nextLine[i]);
}
System.out.println();
}
}
public static void main(String args[]) throws IOException {
writeDataToCsv("./sample.csv");
readDataFromCsv("./sample.csv");
}
}
- Create a CSVReader.
- You can read the CSV file line by line with
readNext()
. An array is returned as many as the number of items.
The execution result is as follows.
0 EW
1 City
2 State
0 W
1 Youngstown
2 OH
0 W
1 Williamson
2 WV
Reference
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)