### Add SLF4J Simple Dependency
Source: https://github.com/42bv/csveed/blob/master/src/site/resources/csveed.html
Use this dependency for quick logging setup if no other SLF4J implementation is configured.
```xml
org.slf4j
slf4j-simple
2.0.0-alpha1
```
--------------------------------
### CSV Data Example
Source: https://github.com/42bv/csveed/blob/master/src/site/resources/rfc4180.html
This example demonstrates a CSV file with leading/trailing spaces around quoted fields and escaped quotes within fields. CSVeed handles these cases correctly.
```csv
first name, surname, street, city, trademark
'Stephen', 'Hawking', '110th Avenue', 'New York', 'History of the \'Universe\''
'Albert', 'Einstein', '', 'Berlin', '\'E\=mc2\''
```
--------------------------------
### Add SLF4J Simple Logger Dependency
Source: https://github.com/42bv/csveed/blob/master/README.md
Add this SLF4J simple logger dependency for quick setup if no other SLF4J logger is configured.
```xml
org.slf4j
slf4j-simple
2.0.7
```
--------------------------------
### Install CSVeed via Maven
Source: https://context7.com/42bv/csveed/llms.txt
Include the CSVeed library and SLF4J logging dependency in your project's pom.xml file.
```xml
org.csveed
csveed
0.7.4
org.slf4j
slf4j-simple
2.0.7
```
--------------------------------
### Specify Start Row in CsvFile
Source: https://github.com/42bv/csveed/wiki/Annotations
Use the startRow attribute in @CsvFile to indicate the first line of data in a CSV file, useful when non-data lines precede the content.
```java
@CsvFile(startRow = 3)
public class Bean {
```
--------------------------------
### ColumnIndexMapper Bean Property Example
Source: https://github.com/42bv/csveed/wiki/Annotations
Defines Bean properties that will be mapped by their column index. Assumes public getters and setters.
```java
private String name;
private Date birthdate;
private Integer creditRating;
```
--------------------------------
### CsvCell columnName Annotation Example
Source: https://github.com/42bv/csveed/wiki/Annotations
Maps a specific CSV header name to a Bean property. Useful for verbose or special character-containing headers.
```java
@CsvCell(columnName = "the first column")
private String first;
@CsvCell(columnName = "my my, how verbose")
private String second;
@CsvCell(columnName = "isn't it?")
private String third;
```
--------------------------------
### CsvCell columnIndex Annotation Example
Source: https://github.com/42bv/csveed/wiki/Annotations
Maps a specific CSV column index to a Bean property. The columnIndex is zero-based. Subsequent properties will use the next available index.
```java
@CsvCell(columnIndex = 4)
private String valuableInfo;
```
--------------------------------
### CsvCell required Annotation Example
Source: https://github.com/42bv/csveed/wiki/Annotations
Marks a Bean property as required. An exception is thrown if the corresponding CSV cell is null or empty.
```java
@CsvCell(required = true)
private String street;
```
--------------------------------
### CsvIgnore Annotation Example
Source: https://github.com/42bv/csveed/wiki/Annotations
Excludes a Bean property from CSV mapping. It will be ignored by both ColumnIndexMapper and ColumnNameMapper.
```java
private String name;
@CsvIgnore
private Date birthdate;
private Integer creditRating;
```
--------------------------------
### Configure Line Endings for CSV Writing
Source: https://context7.com/42bv/csveed/llms.txt
Specify line ending characters (LF or CRLF) when writing CSV files to ensure cross-platform compatibility. This example demonstrates writing with Unix-style LF and Windows-style CRLF.
```java
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import java.io.StringWriter;
// Writing with specific line endings
StringWriter lfWriter = new StringWriter();
CsvClient lfClient = new CsvClientImpl<>(lfWriter)
.setUseHeader(false)
.setEndOfLine(new char[]{'\n'}); // Unix-style LF
lfClient.writeHeader(new String[]{"a", "b", "c"});
lfClient.writeRow(new String[]{"1", "2", "3"});
System.out.println("LF output length: " + lfWriter.toString().length());
// Uses \n for line endings
StringWriter crlfWriter = new StringWriter();
CsvClient crlfClient = new CsvClientImpl<>(crlfWriter)
.setUseHeader(false)
.setEndOfLine(new char[]{'
', '\n'}); // Windows-style CRLF
crlfClient.writeHeader(new String[]{"a", "b", "c"});
crlfClient.writeRow(new String[]{"1", "2", "3"});
System.out.println("CRLF output length: " + crlfWriter.toString().length());
// Uses \r\n for line endings (2 extra characters)
```
--------------------------------
### Deploy to Sonatype OSS Repository
Source: https://github.com/42bv/csveed/wiki/Releasing-to-Maven-Central
Execute this Maven command to clean the project and deploy the release artifacts to the Sonatype OSS repository.
```bash
mvn clean deploy -P sonatype-oss-release
```
--------------------------------
### Initialize CsvClient with Bean Class
Source: https://github.com/42bv/csveed/blob/master/src/site/resources/annotations.html
Instantiate CsvClient by passing the reader and the Bean class. This is required for annotations to work.
```java
CsvClient csvReader = new CsvClientImpl(reader, Bean.class);
```
--------------------------------
### Create and Push Git Tag
Source: https://github.com/42bv/csveed/wiki/Releasing-to-Maven-Central
Use this command to create an annotated tag for a new version and push it to the remote repository.
```bash
git tag -a v0.x.0 -m "Version 0.x.0 Stable"
git push --tags
```
--------------------------------
### Initialize CsvReader with Bean Class
Source: https://github.com/42bv/csveed/wiki/Annotations
Pass the Bean class to CsvReaderImpl for annotation processing.
```java
CsvReader csvReader = new CsvReaderImpl(reader, Bean.class);
```
--------------------------------
### Read CSV Beans using Programmatic Configuration
Source: https://github.com/42bv/csveed/blob/master/src/site/resources/csveed.html
Configure mapping instructions programmatically instead of using annotations on the bean class.
```java
Reader reader = new StringReader(
"name;number;date\n"+
"\"Alpha\";1900;\"13-07-1922\"\n"+
"\"Beta\";1901;\"22-01-1943\"\n"+
"\"Gamma\";1902;\"30-09-1978\""
);
CsvClient csvReader = new CsvClientImpl(reader,
new BeanReaderInstructionsImpl(Bean.class))
.setMapper(ColumnNameMapper.class)
.mapColumnNameToProperty("name", "name")
.mapColumnNameToProperty("number", "number")
.mapColumnNameToProperty("date", "date")
.setDate("date", "dd-MM-yyyy");
final List beans = csvReader.readBeans();
for (Bean bean : beans) {
System.out.println(
bean.getName()+" | " +
bean.getNumber()+" | "+
bean.getDate());
}
```
--------------------------------
### Read CSV Beans with Programmatic Instructions
Source: https://github.com/42bv/csveed/blob/master/README.md
Configure CSV reading programmatically by setting the mapper, mapping column names to properties, and defining date formats.
```java
Reader reader = new StringReader(
"name;number;date\n"+
"\"Alpha\";1900;\"13-07-1922\"\n"+
"\"Beta\";1901;\"22-01-1943\"\n"+
"\"Gamma\";1902;\"30-09-1978\"
);
CsvClient csvClient = new CsvClientImpl(reader, new BeanInstructionsImpl(Bean.class))
.setMapper(ColumnNameMapper.class)
.mapColumnNameToProperty("name", "name")
.mapColumnNameToProperty("number", "number")
.mapColumnNameToProperty("date", "date")
.setDate("date", "dd-MM-yyyy");
final List beans = csvClient.readBeans();
for (Bean bean : beans) {
System.out.println(bean.getName()+" | "+bean.getNumber()+" | "+bean.getDate());
}
```
--------------------------------
### Configure CSV file parsing options
Source: https://github.com/42bv/csveed/blob/master/src/site/resources/annotations.html
Use @CsvFile to toggle the default behavior for skipping empty lines and comment lines.
```java
@CsvFile(skipCommentLines = false, skipEmptyLines = false)
public class Bean {
```
--------------------------------
### Configure CSV Parsing with Fluent API
Source: https://context7.com/42bv/csveed/llms.txt
Chain configuration methods on CsvClientImpl to define separators, row handling, and bean mapping rules. This approach allows for complex parsing logic without requiring additional annotations.
```java
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import org.csveed.bean.ColumnNameMapper;
import java.io.StringReader;
import java.util.List;
import java.util.Locale;
public class Report {
private String title;
private Double value;
private java.util.Date reportDate;
// Getters and setters
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public Double getValue() { return value; }
public void setValue(Double value) { this.value = value; }
public java.util.Date getReportDate() { return reportDate; }
public void setReportDate(java.util.Date reportDate) { this.reportDate = reportDate; }
}
String csv = "% Header comment\n" +
"% Another comment\n" +
"title,value,reportDate\n" +
"'Q1 Report','1.234,56','15-01-2024'\n" +
"'Q2 Report','2.345,67','15-04-2024'";
CsvClient csvClient = new CsvClientImpl<>(new StringReader(csv), Report.class)
// Parse settings
.setSeparator(',') // Column separator
.setQuote('\'') // Quote character
.setEscape('\\') // Escape character
.setComment('%') // Comment line marker
.setEndOfLine(new char[]{'\n'}) // End of line characters
// Row handling
.setStartRow(3) // Start at row 3 (skip comments)
.setUseHeader(true) // First content row is header
.skipEmptyLines(true) // Skip empty lines
.skipCommentLines(true) // Skip comment lines
// Bean mapping
.setMapper(ColumnNameMapper.class)
.setDate("reportDate", "dd-MM-yyyy")
.setLocalizedNumber("value", Locale.GERMANY)
.setRequired("title", true);
List reports = csvClient.readBeans();
for (Report report : reports) {
System.out.println(report.getTitle() + ": " + report.getValue());
}
// Output:
// Q1 Report: 1234.56
// Q2 Report: 2345.67
```
--------------------------------
### Programmatic CSV Parsing Configuration with BeanInstructions
Source: https://context7.com/42bv/csveed/llms.txt
Configure CSV parsing rules programmatically using BeanInstructions for runtime flexibility, allowing mapping of columns to properties, setting separators, and defining date formats without annotations. This approach is useful when annotations are not feasible or for dynamic configurations.
```java
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import org.csveed.bean.BeanInstructionsImpl;
import org.csveed.bean.ColumnNameMapper;
import java.io.StringReader;
import java.util.List;
// Plain bean without annotations
public class Transaction {
private String transactionId;
private String customerName;
private Double amount;
private java.util.Date transactionDate;
// Getters and setters
public String getTransactionId() { return transactionId; }
public void setTransactionId(String transactionId) { this.transactionId = transactionId; }
public String getCustomerName() { return customerName; }
public void setCustomerName(String customerName) { this.customerName = customerName; }
public Double getAmount() { return amount; }
public void setAmount(Double amount) { this.amount = amount; }
public java.util.Date getTransactionDate() { return transactionDate; }
public void setTransactionDate(java.util.Date transactionDate) { this.transactionDate = transactionDate; }
}
String csv = "tx_id,customer,value,date\n" +
"\"TXN001\";\"Alice\";\"150.00\";\"2024-01-15\"\n" +
"\"TXN002\";\"Bob\";\"275.50\";\"2024-01-16\"";
// Configure programmatically
BeanInstructionsImpl instructions = new BeanInstructionsImpl(Transaction.class);
CsvClient csvClient = new CsvClientImpl<>(new StringReader(csv), instructions)
.setSeparator(',') // Use comma separator
.setMapper(ColumnNameMapper.class) // Map by column name
.mapColumnNameToProperty("tx_id", "transactionId") // Map CSV column to property
.mapColumnNameToProperty("customer", "customerName")
.mapColumnNameToProperty("value", "amount")
.mapColumnNameToProperty("date", "transactionDate")
.setDate("transactionDate", "yyyy-MM-dd") // Set date format
.setRequired("transactionId", true); // Mark as required
List transactions = csvClient.readBeans();
for (Transaction tx : transactions) {
System.out.println(tx.getTransactionId() + ": " + tx.getCustomerName() + " - $" + tx.getAmount());
}
// Output:
// TXN001: Alice - $150.0
// TXN002: Bob - $275.5
```
--------------------------------
### Read CSV Beans using Annotations
Source: https://github.com/42bv/csveed/blob/master/src/site/resources/csveed.html
Initialize the CsvClient with a reader and the bean class to parse CSV data automatically.
```java
Reader reader = new StringReader(
"name;number;date\n"+
"\"Alpha\";1900;\"13-07-1922\"\n"+
"\"Beta\";1901;\"22-01-1943\"\n"+
"\"Gamma\";1902;\"30-09-1978\""
);
CsvClient csvReader = new CsvClientImpl(reader, Bean.class);
final List beans = csvReader.readBeans();
for (Bean bean : beans) {
System.out.println(
bean.getName()+" | " +
bean.getNumber()+" | "+
bean.getDate());
}
```
--------------------------------
### Implement Custom PropertyEditor
Source: https://github.com/42bv/csveed/wiki/Annotations
Extend PropertyEditorSupport to create custom converters for mapping between strings and object properties.
```java
public class BeanSimplePropertyEditor extends PropertyEditorSupport {
public String getAsText() {
return ((BeanSimple)getValue()).getName();
}
public void setAsText(String text) {
BeanSimple bean = new BeanSimple();
bean.setName(text);
setValue(bean);
}
}
```
--------------------------------
### Configure CsvFile Parse Instructions
Source: https://github.com/42bv/csveed/blob/master/src/site/resources/annotations.html
Use the CsvFile annotation on a Bean class to specify parse instructions like comment, quote, escape, separator, and end-of-line characters for CSV files.
```java
@CsvFile(comment = '%', quote='\'', escape='\\', separator=',')
public class Bean {
```
--------------------------------
### Configure CsvFile Parse Instructions
Source: https://github.com/42bv/csveed/wiki/Annotations
Annotate the Bean class with @CsvFile to specify custom parsing characters like comment, quote, and escape.
```java
@CsvFile(comment = '%', quote='\'', escape='\\', separator=',')
public class Bean {
```
--------------------------------
### Define Java Bean with Annotations
Source: https://github.com/42bv/csveed/blob/master/src/site/resources/csveed.html
Create a Java class to represent CSV rows, using annotations like @CsvDate for custom data conversion.
```java
import org.csveed.annotations.CsvDate;
import java.util.Date;
public class Bean {
private String name;
private Long number;
@CsvDate(format="dd-MM-yyyy")
private Date date;
public String getName() { return name; }
public Long getNumber() { return number; }
public Date getDate() { return date; }
public void setName(String name) { this.name = name; }
public void setNumber(Long number) { this.number = number; }
public void setDate(Date date) { this.date = date; }
}
```
--------------------------------
### Map Dynamic CSV Columns with Annotations
Source: https://context7.com/42bv/csveed/llms.txt
Use @CsvHeaderName and @CsvHeaderValue to transform dynamic columns into individual bean instances. The startIndexDynamicColumns attribute in @CsvFile defines where dynamic processing begins.
```java
import org.csveed.annotations.CsvFile;
import org.csveed.annotations.CsvHeaderName;
import org.csveed.annotations.CsvHeaderValue;
import org.csveed.bean.ColumnNameMapper;
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import java.io.StringReader;
import java.util.List;
@CsvFile(mappingStrategy = ColumnNameMapper.class, startIndexDynamicColumns = 2)
public class SalesData {
private String product;
private String region;
@CsvHeaderName
private String month; // Receives the header name (e.g., "Jan", "Feb", "Mar")
@CsvHeaderValue
private Integer salesAmount; // Receives the cell value for that month
// Getters and setters
public String getProduct() { return product; }
public void setProduct(String product) { this.product = product; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public String getMonth() { return month; }
public void setMonth(String month) { this.month = month; }
public Integer getSalesAmount() { return salesAmount; }
public void setSalesAmount(Integer salesAmount) { this.salesAmount = salesAmount; }
}
// CSV with dynamic columns (Jan, Feb, Mar are dynamic)
String csv = "product;region;Jan;Feb;Mar\n" +
"\"Laptop\";\"North\";100;150;120\n" +
"\"Laptop\";\"South\";80;90;110";
CsvClient csvClient = new CsvClientImpl<>(new StringReader(csv), SalesData.class);
List salesData = csvClient.readBeans();
// Each row creates 3 beans (one per dynamic column)
for (SalesData sale : salesData) {
System.out.println(sale.getProduct() + " | " + sale.getRegion() +
" | " + sale.getMonth() + ": " + sale.getSalesAmount());
}
// Output:
// Laptop | North | Jan: 100
// Laptop | North | Feb: 150
// Laptop | North | Mar: 120
// Laptop | South | Jan: 80
// Laptop | South | Feb: 90
// Laptop | South | Mar: 110
```
--------------------------------
### Implement BeanSimpleConverter in Java
Source: https://github.com/42bv/csveed/wiki/notes
This Java code defines a converter for BeanSimple objects. It overrides the fromString method to create a BeanSimple instance from a string and getType to return the class type.
```java
public class BeanSimpleConverter extends AbstractConverter {
@Override
public BeanSimple fromString(String text) throws Exception {
return new BeanSimple(text);
}
@Override
public Class getType() {
return BeanSimple.class;
}
}
```
--------------------------------
### Configure Line Skipping in CsvFile
Source: https://github.com/42bv/csveed/wiki/Annotations
Control whether empty lines and comment lines are skipped by setting skipEmptyLines and skipCommentLines to false in @CsvFile.
```java
@CsvFile(skipCommentLines = false, skipEmptyLines = false)
public class Bean {
```
--------------------------------
### Write Java Beans to CSV
Source: https://context7.com/42bv/csveed/llms.txt
Use CsvClient to serialize a list of Java objects into a CSV format, automatically generating headers from bean properties.
```java
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
public class Product {
private String name;
private Double price;
private Integer quantity;
public Product(String name, Double price, Integer quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
// Getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Double getPrice() { return price; }
public void setPrice(Double price) { this.price = price; }
public Integer getQuantity() { return quantity; }
public void setQuantity(Integer quantity) { this.quantity = quantity; }
}
// Write beans to CSV
StringWriter writer = new StringWriter();
List products = new ArrayList<>();
products.add(new Product("Laptop", 999.99, 50));
products.add(new Product("Mouse", 29.99, 200));
products.add(new Product("Keyboard", 79.99, 150));
CsvClient csvClient = new CsvClientImpl<>(writer, Product.class);
csvClient.writeBeans(products);
System.out.println(writer.toString());
```
--------------------------------
### Configure CSV Parsing with @CsvFile Annotation
Source: https://context7.com/42bv/csveed/llms.txt
The @CsvFile annotation configures parsing behavior like separators, quotes, escapes, and mapping strategy. Imports required: CsvFile, ColumnNameMapper, CsvClient, CsvClientImpl, StringReader, List.
```java
import org.csveed.annotations.CsvFile;
import org.csveed.bean.ColumnNameMapper;
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import java.io.StringReader;
import java.util.List;
@CsvFile(
separator = ',', // Use comma as separator (default is semicolon)
quote = '\'', // Use single quote for quoting fields
escape = '\\', // Use backslash for escaping quotes
comment = '%', // Use % for comment lines
useHeader = true, // First line is header
startRow = 1, // Start reading from row 1 (1-based)
skipEmptyLines = true, // Skip empty lines
skipCommentLines = true, // Skip comment lines
mappingStrategy = ColumnNameMapper.class // Map by column name
)
public class Employee {
private String firstName;
private String lastName;
private String department;
// Getters and setters
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String getDepartment() { return department; }
public void setDepartment(String department) { this.department = department; }
}
String csv = "firstName,lastName,department\n" +
"% This is a comment line\n" +
"'John','Doe','Engineering'\n" +
"'Jane','Smith','Marketing'";
CsvClient csvClient = new CsvClientImpl<>(new StringReader(csv), Employee.class);
List employees = csvClient.readBeans();
for (Employee emp : employees) {
System.out.println(emp.getFirstName() + " " + emp.getLastName() + " - " + emp.getDepartment());
}
// Output:
// John Doe - Engineering
// Jane Smith - Marketing
```
--------------------------------
### Read CSV Beans using Annotations
Source: https://github.com/42bv/csveed/blob/master/README.md
Read CSV data into Java Beans using annotations for mapping and date parsing. Requires a configured Reader and the Bean class.
```java
Reader reader = new StringReader(
"name;number;date\n"+
"\"Alpha\";1900;\"13-07-1922\"\n"+
"\"Beta\";1901;\"22-01-1943\"\n"+
"\"Gamma\";1902;\"30-09-1978\"
);
CsvClient csvClient = new CsvClientImpl(reader, Bean.class);
final List beans = csvClient.readBeans();
for (Bean bean : beans) {
System.out.println(bean.getName()+" | "+bean.getNumber()+" | "+bean.getDate());
}
```
--------------------------------
### Read CSV Data as Raw Rows
Source: https://context7.com/42bv/csveed/llms.txt
Use this when direct access to cell values is needed or when a predefined bean structure is unavailable. Imports required: CsvClient, CsvClientImpl, Row, Header, Reader, StringReader, List.
```java
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import org.csveed.api.Row;
import org.csveed.api.Header;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;
Reader reader = new StringReader(
"product;category;price\n" +
"\"Laptop\";\"Electronics\";\"999.99\"\n" +
"\"Chair\";\"Furniture\";\"149.99\"\n" +
"\"Book\";\"Education\";\"29.99\"
);
CsvClient csvClient = new CsvClientImpl<>(reader);
Header header = csvClient.readHeader();
List rows = csvClient.readRows();
// Access header columns
System.out.println("Columns: " + header.size()); // Output: 3
System.out.println("First column: " + header.getName(1)); // Output: product
// Iterate through rows
for (Row row : rows) {
// Access by column index (1-based)
String product = row.get(1);
// Access by column name
String category = row.get("category");
String price = row.get("price");
System.out.println(product + " (" + category + "): $" + price);
}
// Output:
// Laptop (Electronics): $999.99
// Chair (Furniture): $149.99
// Book (Education): $29.99
```
--------------------------------
### Map CSV Columns by Index with @CsvCell
Source: https://context7.com/42bv/csveed/llms.txt
Use @CsvCell with columnIndex to map CSV columns to bean properties. The annotation uses 1-based indexing, while the mapping is 0-based. Fields can be marked as required.
```java
import org.csveed.annotations.CsvCell;
import org.csveed.annotations.CsvFile;
import org.csveed.bean.ColumnIndexMapper;
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import java.io.StringReader;
// Using column index mapping (0-based columns, but 1-based in annotation)
@CsvFile(useHeader = false, mappingStrategy = ColumnIndexMapper.class)
public class DataRecord {
@CsvCell(columnIndex = 1)
private String id;
@CsvCell(columnIndex = 3) // Skip column 2
private String name;
@CsvCell(columnIndex = 5, required = true) // Must not be empty
private String value;
// Getters and setters
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
}
String csv = ""ID001";"skip";"Product A";"skip";"100"";
CsvClient csvClient = new CsvClientImpl<>(new StringReader(csv), DataRecord.class);
DataRecord record = csvClient.readBean();
System.out.println("ID: " + record.getId()); // Output: ID001
System.out.println("Name: " + record.getName()); // Output: Product A
System.out.println("Value: " + record.getValue()); // Output: 100
```
--------------------------------
### Specifying date formats
Source: https://github.com/42bv/csveed/blob/master/src/site/resources/annotations.html
Use @CsvDate to define the date format string for parsing java.util.Date fields.
```java
@CsvDate(format = "dd-MM-yyyy")
private String date;
```
--------------------------------
### Add CSVeed Maven Dependency
Source: https://github.com/42bv/csveed/blob/master/src/site/resources/csveed.html
Include this dependency in your project's pom.xml to use the CSVeed library.
```xml
com.github.hazendaz
csveed
0.7.0
```
--------------------------------
### Define Java Bean for CSV Data
Source: https://github.com/42bv/csveed/blob/master/README.md
Define a Java Bean with properties that correspond to CSV columns. Use @CsvDate annotation for date formatting.
```java
import org.csveed.annotations.CsvDate;
import java.util.Date;
public class Bean {
private String name;
private Long number;
@CsvDate(format="dd-MM-yyyy")
private Date date;
public String getName() { return name; }
public Long getNumber() { return number; }
public Date getDate() { return date; }
public void setName(String name) { this.name = name; }
public void setNumber(Long number) { this.number = number; }
public void setDate(Date date) { this.date = date; }
}
```
--------------------------------
### Map CSV Columns by Name with @CsvCell
Source: https://context7.com/42bv/csveed/llms.txt
Use @CsvCell with columnName to map CSV headers to bean properties. This is useful for verbose or non-standard CSV headers. Ensure the CSV file has a header row.
```java
import org.csveed.annotations.CsvCell;
import org.csveed.annotations.CsvFile;
import org.csveed.bean.ColumnNameMapper;
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import java.io.StringReader;
@CsvFile(mappingStrategy = ColumnNameMapper.class)
public class CustomerRecord {
@CsvCell(columnName = "Customer Full Name")
private String name;
@CsvCell(columnName = "E-Mail Address")
private String email;
@CsvCell(columnName = "Phone #")
private String phone;
// Getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; }
}
String csv = "Customer Full Name;E-Mail Address;Phone #\n" +
""John Doe";"john@example.com";"555-1234"";
CsvClient csvClient = new CsvClientImpl<>(new StringReader(csv), CustomerRecord.class);
CustomerRecord customer = csvClient.readBean();
System.out.println("Name: " + customer.getName()); // Output: John Doe
System.out.println("Email: " + customer.getEmail()); // Output: john@example.com
System.out.println("Phone: " + customer.getPhone()); // Output: 555-1234
```
--------------------------------
### Add CSVeed Maven Dependency
Source: https://github.com/42bv/csveed/blob/master/README.md
Include this dependency in your Maven project to use the CSVeed library.
```xml
org.csveed
csveed
0.7.4
```
--------------------------------
### Format Dates with @CsvDate Annotation
Source: https://context7.com/42bv/csveed/llms.txt
Use the @CsvDate annotation to specify the date format pattern for parsing date values. Supports SimpleDateFormat syntax for various date and time formats.
```java
import org.csveed.annotations.CsvDate;
import org.csveed.annotations.CsvFile;
import org.csveed.bean.ColumnNameMapper;
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import java.io.StringReader;
import java.util.Date;
import java.text.SimpleDateFormat;
@CsvFile(mappingStrategy = ColumnNameMapper.class)
public class Event {
private String name;
@CsvDate(format = "yyyy-MM-dd")
private Date startDate;
@CsvDate(format = "dd/MM/yyyy HH:mm")
private Date deadline;
@CsvDate(format = "yyyy-MM")
private Date monthYear;
// Getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Date getStartDate() { return startDate; }
public void setStartDate(Date startDate) { this.startDate = startDate; }
public Date getDeadline() { return deadline; }
public void setDeadline(Date deadline) { this.deadline = deadline; }
public Date getMonthYear() { return monthYear; }
public void setMonthYear(Date monthYear) { this.monthYear = monthYear; }
}
String csv = "name;startDate;deadline;monthYear\n" +
""Project Launch";"2024-03-15";"31/03/2024 23:59";"2024-03"";
CsvClient csvClient = new CsvClientImpl<>(new StringReader(csv), Event.class);
Event event = csvClient.readBean();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
System.out.println("Event: " + event.getName());
System.out.println("Start: " + dateFormat.format(event.getStartDate()));
System.out.println("Deadline: " + dateTimeFormat.format(event.getDeadline()));
// Output:
// Event: Project Launch
// Start: 2024-03-15
// Deadline: 31/03/2024 23:59
```
--------------------------------
### Define CSV Date Format
Source: https://github.com/42bv/csveed/wiki/Annotations
Use the CsvDate annotation to specify a custom date format for string-to-date conversion.
```java
@CsvDate(format = "dd-MM-yyyy")
private String date;
```
--------------------------------
### Write Raw Rows to CSV
Source: https://context7.com/42bv/csveed/llms.txt
Write raw string arrays or Row objects directly to CSV format without bean mapping. Imports required: CsvClient, CsvClientImpl, StringWriter.
```java
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import java.io.StringWriter;
StringWriter writer = new StringWriter();
CsvClient csvClient = new CsvClientImpl<>(writer);
// Write header
csvClient.writeHeader(new String[]{"name", "department", "salary"});
// Write multiple rows as 2D array
String[][] data = {
{"Alice Johnson", "Engineering", "85000"},
{"Bob Smith", "Marketing", "72000"},
{"Carol White", "Finance", "78000"}
};
csvClient.writeRows(data);
System.out.println(writer.toString());
// Output:
// "name";"department";"salary"
// "Alice Johnson";"Engineering";"85000"
// "Bob Smith";"Marketing";"72000"
// "Carol White";"Finance";"78000"
```
--------------------------------
### Read CSV Data into Java Beans
Source: https://context7.com/42bv/csveed/llms.txt
Use CsvClient to map CSV rows to annotated Java objects. The @CsvDate annotation handles custom date formatting during conversion.
```java
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import org.csveed.annotations.CsvDate;
import java.io.Reader;
import java.io.StringReader;
import java.util.Date;
import java.util.List;
// Define a bean class with annotations
public class Person {
private String name;
private Long employeeId;
@CsvDate(format = "dd-MM-yyyy")
private Date birthDate;
// Getters and setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Long getEmployeeId() { return employeeId; }
public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; }
public Date getBirthDate() { return birthDate; }
public void setBirthDate(Date birthDate) { this.birthDate = birthDate; }
}
// Read CSV data into beans
Reader reader = new StringReader(
"name;employeeId;birthDate\n" +
"\"John Doe\";1001;\"15-03-1985\"\n" +
"\"Jane Smith\";1002;\"22-08-1990\"\n" +
"\"Bob Wilson\";1003;\"30-12-1978\""
);
CsvClient csvClient = new CsvClientImpl<>(reader, Person.class);
List people = csvClient.readBeans();
for (Person person : people) {
System.out.println(person.getName() + " | ID: " + person.getEmployeeId() + " | Born: " + person.getBirthDate());
}
```
--------------------------------
### @CsvDate Annotation - Date Formatting
Source: https://context7.com/42bv/csveed/llms.txt
Specifies the date format pattern for parsing date values from CSV strings into Java Date objects.
```APIDOC
## @CsvDate
### Description
Defines the date format pattern for a field using SimpleDateFormat syntax to correctly parse date strings from the CSV.
### Parameters
#### Field Annotations
- **format** (string) - Required - The date pattern (e.g., "yyyy-MM-dd") used to parse the CSV string value.
```
--------------------------------
### @CsvCell Annotation - Column Name Mapping
Source: https://context7.com/42bv/csveed/llms.txt
Maps CSV columns to bean properties based on the header name found in the CSV file.
```APIDOC
## @CsvCell (Name Mapping)
### Description
Maps bean fields to CSV columns by matching the header name defined in the annotation to the header row in the CSV.
### Parameters
#### Field Annotations
- **columnName** (string) - Required - The exact header name in the CSV file to map to this field.
```
--------------------------------
### Disable Header for CsvFile
Source: https://github.com/42bv/csveed/wiki/Annotations
Set useHeader to false in @CsvFile when the CSV file lacks a header row. This prevents using ColumnNameMapping.
```java
@CsvFile(useHeader = false)
public class Bean {
```
--------------------------------
### @CsvCell Annotation - Column Index Mapping
Source: https://context7.com/42bv/csveed/llms.txt
Maps CSV columns to bean properties using 1-based column indices. Supports marking fields as required.
```APIDOC
## @CsvCell (Index Mapping)
### Description
Maps specific CSV columns to bean fields based on their index position. The index is 1-based.
### Parameters
#### Field Annotations
- **columnIndex** (int) - Required - The 1-based index of the column in the CSV.
- **required** (boolean) - Optional - If true, the field must not be empty.
```
--------------------------------
### Custom Type Conversion with @CsvConverter
Source: https://context7.com/42bv/csveed/llms.txt
Implement the Converter interface to handle complex data types. Use @CsvConverter on bean fields to specify the custom converter class.
```java
import org.csveed.annotations.CsvConverter;
import org.csveed.bean.conversion.Converter;
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import java.io.StringReader;
// Custom object to convert to
public class Address {
private String street;
private String city;
private String zipCode;
public Address(String street, String city, String zipCode) {
this.street = street;
this.city = city;
this.zipCode = zipCode;
}
public String getStreet() { return street; }
public String getCity() { return city; }
public String getZipCode() { return zipCode; }
@Override
public String toString() {
return street + ", " + city + " " + zipCode;
}
}
// Custom converter implementation
public class AddressConverter implements Converter {
@Override
public Address fromString(String text) {
// Parse "street|city|zipcode" format
String[] parts = text.split("\\|");
return new Address(parts[0].trim(), parts[1].trim(), parts[2].trim());
}
@Override
public String toString(Address address) {
return address.getStreet() + "|" + address.getCity() + "|" + address.getZipCode();
}
@Override
public String infoOnType() { return "Address (street|city|zipcode)"; }
@Override
public Class getType() { return Address.class; }
}
// Bean using the custom converter
public class Contact {
private String name;
@CsvConverter(converter = AddressConverter.class)
private Address address;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Address getAddress() { return address; }
public void setAddress(Address address) { this.address = address; }
}
String csv = "name;address\n" +
"\"John Doe\";\"123 Main St|New York|10001\"";
CsvClient csvClient = new CsvClientImpl<>(new StringReader(csv), Contact.class);
Contact contact = csvClient.readBean();
System.out.println("Name: " + contact.getName());
System.out.println("Address: " + contact.getAddress());
// Output:
// Name: John Doe
// Address: 123 Main St, New York 10001
```
--------------------------------
### Exclude Bean Properties with @CsvIgnore
Source: https://context7.com/42bv/csveed/llms.txt
Use @CsvIgnore to prevent specific fields from being mapped to or from CSV files. Ignored fields remain null during reading and are omitted during writing.
```java
import org.csveed.annotations.CsvIgnore;
import org.csveed.api.CsvClient;
import org.csveed.api.CsvClientImpl;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;
public class OrderItem {
private String productName;
private Double unitPrice;
private Integer quantity;
@CsvIgnore
private Double totalPrice; // Calculated, not in CSV
@CsvIgnore
private String internalCode; // Internal use only
public void calculateTotal() {
this.totalPrice = unitPrice * quantity;
}
// Getters and setters
public String getProductName() { return productName; }
public void setProductName(String productName) { this.productName = productName; }
public Double getUnitPrice() { return unitPrice; }
public void setUnitPrice(Double unitPrice) { this.unitPrice = unitPrice; }
public Integer getQuantity() { return quantity; }
public void setQuantity(Integer quantity) { this.quantity = quantity; }
public Double getTotalPrice() { return totalPrice; }
public String getInternalCode() { return internalCode; }
public void setInternalCode(String internalCode) { this.internalCode = internalCode; }
}
// Reading - ignored fields stay null
String csv = "productName;unitPrice;quantity\n" +
"\"Widget\";\"19.99\";\"5\"";
CsvClient reader = new CsvClientImpl<>(new StringReader(csv), OrderItem.class);
OrderItem item = reader.readBean();
item.calculateTotal();
System.out.println(item.getProductName() + " x " + item.getQuantity() +
" = $" + item.getTotalPrice());
// Output: Widget x 5 = $99.95
// Writing - ignored fields are excluded from output
item.setInternalCode("INT-001");
StringWriter writer = new StringWriter();
CsvClient csvWriter = new CsvClientImpl<>(writer, OrderItem.class);
csvWriter.writeBean(item);
System.out.println(writer.toString());
// Output (no totalPrice or internalCode columns):
// "quantity";"unitPrice";"productName"
// "5";"19.99";"Widget"
```