Application example of the SimpleCSV framework in Java Library
SimpleCSV is a Java class library for handling CSV files.It provides easy -to -use methods and functions that can easily read and write CSV files.
The following is an application example using the SimpleCSV framework, which shows how to read and process CSV files with SimpleCSV:
Suppose there is a CSV file called Student.csv, which contains the student's name and age information.The content of the file is as follows:
Name, age
Zhang San, 18
Li Si, 20
Wang Wu, 22
In the Java code, we first need to import the relevant class of the SimpleCSV library:
import com.github.mygreen.supercsv.io.CsvAnnotationBeanReader;
import com.github.mygreen.supercsv.io.CsvAnnotationBeanWriter;
import com.github.mygreen.supercsv.io.CsvAnnotationBeanWriterFactory;
import com.github.mygreen.supercsv.io.CsvException;
import com.github.mygreen.supercsv.io.CsvNullConverter;
import com.github.mygreen.supercsv.io.CsvReader;
import com.github.mygreen.supercsv.io.CsvWriter;
Then, we define a Java class called Student for storing student information:
public class Student {
private String name;
private int age;
// omit the creation function and getter/setter method
@Csvcolumn (NUMBER = 1, Label = "Name")
public String getName() {
return name;
}
@Csvcolumn (number = 2, label = "age")
public int getAge() {
return age;
}
}
Below is a simplecsv read CSV file and convert it into a sample code containing a list of student objects:
public class SimplecsvExample {
public static void main(String[] args) {
try (CsvReader csvReader = CsvAnnotationBeanReader.fromMapping(Student.class).open(new File("student.csv"))) {
List<Student> students = new ArrayList<>();
Student student;
while ((student = csvReader.read(Student.class)) != null) {
students.add(student);
}
// Print students list
for (Student s : students) {
System.out.println ("Name:" + s.getName () + ", age:" + s.get ());
}
} catch (IOException | CsvException e) {
e.printStackTrace();
}
}
}
The above code reads data from the Student.csv file through the `csvannotationbeanReader` class, and uses the` csvcolumn` annotation to map the column in the CSV file to the attributes of the Student class.Read each line of data by circulating, and use the `csvreader.read (student.class) method to convert the CSV row to the Student object.Finally, add the conversion of the Student object to a list and print the student list.
Through the above examples, we can see that the SimplecsV framework provides a simple and easy -to -use API, which can easily read and process CSV files.You can use the SimpleCSV framework to handle more complex CSV file processing according to your needs.