Today I will share with you a Java operation CSV file using external Jar packages
1. Resource download
1. Download the Jar package directly: javacsv-2.0.jar
2. Use Maven to download the Jar package:
<dependency> <groupId>net.sourceforge.javacsv</groupId> <artifactId>javacsv</artifactId> <version>2.0</version></dependency>
3. API description: javacsv.sourceforge.net
2. Operation demonstration
1. Write a case for CSV file
public static void writeCSV() { // Define a CSV path String csvFilePath = "D://StemQ.csv"; try { // Create a CSV write object, for example: CsvWriter(file path, separator, encoding format); CsvWriter csvWriter = new CsvWriter(csvFilePath, ',', Charset.forName("UTF-8")); // Write header String[] csvHeaders = { "number", "name", "age" }; csvWriter.writeRecord(csvHeaders); // Write content for (int i = 0; i < 20; i++) { String[] csvContent = { i + "000000", "StemQ", "1" + i }; csvWriter.writeRecord(csvContent); } csvWriter.close(); System.out.println("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------2. Read CSV file cases
public static void readCSV() { try { // Used to save data ArrayList<String[]> csvFileList = new ArrayList<String[]>(); // Define a CSV path String csvFilePath = "D://StemQ.csv"; // Create a CSV read object such as: CsvReader(file path, separator, encoding format); CsvReader reader = new CsvReader(csvFilePath, ',', Charset.forName("UTF-8")); // Skip the table header If the table header is needed, this sentence can ignore reader.readHeaders(); // Read the data with the table header row by row while (reader.readRecord()) { System.out.println(reader.getRawRecord()); csvFileList.add(reader.getValues()); } reader.close(); // traverse the read CSV file for (int row = 0; row < csvFileList.size(); row++) { // Get the data in the 0th column of row String cell = csvFileList.get(row)[0]; System.out.println("------------>"+cell); } } catch (IOException e) { e.printStackTrace(); }}3. Summary
The above content is a simple example of using JavaCSV.jar operations, which can be modified as appropriate according to your project needs.