How do I retrieve values from a CSV file using Java?
In Java, you can use a CSV parsing library to read values from a CSV file. Here is an example code using Apache Commons CSV library to read a CSV file.
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.FileReader;
import java.io.IOException;
public class ReadCSV {
public static void main(String[] args) {
String csvFilePath = "path/to/your/csv/file.csv";
try (FileReader reader = new FileReader(csvFilePath);
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT)) {
for (CSVRecord csvRecord : csvParser) {
String column1 = csvRecord.get(0); // 获取第一列的值
String column2 = csvRecord.get(1); // 获取第二列的值
// ...
System.out.println("Value from column 1: " + column1);
System.out.println("Value from column 2: " + column2);
// ...
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Make sure that you have added the Apache Commons CSV library to your project. You can add the dependency using build tools such as Maven or Gradle.