The file format requirements and instructions of the CSV extension framework in the Java class library
CSV (comma separation value) is a common file format that is used to store and exchange data from commas.The CSV expansion framework in the Java library provides a more convenient and flexible way when processing the CSV file.
File format requirements:
1. File extension is usually .csv.
2. Each row represents a record, and the field is separated in a comma.
3. All fields can be wrapped in quotes to avoid ambiguity in the content of the comma.
4. The quotes in the quotation marks need to be righteous.
The following is a sample CSV file:
csv
Name, age, city
"Zhang San", 25, "Beijing"
"Li Si", 30, "Shanghai"
Java code example:
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
public class CSVExample {
public static void readCSV(String filePath) {
try (CSVReader reader = new CSVReader(new FileReader(filePath))) {
List<String[]> records = reader.readAll();
for (String[] record : records) {
for (String field : record) {
System.out.print(field + " ");
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeCSV(String filePath) {
try (CSVWriter writer = new CSVWriter(new FileWriter(filePath))) {
String [] header = {"name", "age", "city"};
writer.writeNext(header);
String [] record1 = {"Zhang San", "25", "Beijing"};
String [] Record2 = {"Li Si", "30", "Shanghai"};
writer.writeNext(record1);
writer.writeNext(record2);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String filePath = "example.csv";
writeCSV(filePath);
readCSV(filePath);
}
}
In the above example, we use the `OpenCSV` class library to read and write into the CSV file.`CSVReader` is used to read CSV files, and` csvwriter` is used to write CSV files.The `Readcsv` method reads the data from the CSV file and prints it to the console.In the `Main` method, we first use the` writecsv` method to create a sample CSV file, and then read the content of the file with the `readcsv` method and print it.