最好的方法是使用 CSVWriter。如果您有一个 Maven 项目,请将其添加为依赖项:
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.4</version>
</dependency>
然后你可以像这样使用它:
try {
//the list that contains the String arrays
List<String[]> whatever = new ArrayList<>();
CSVWriter writer = new CSVWriter(new FileWriter(csvFilename));
String[] header = "Name,Age,Height,etc..".split(",");
writer.writeNext(header);
writer.writeAll(whatever, true); //And the second argument is boolean which represents whether you want to write header columns (table column names) to file or not.
writer.close();
System.out.println("CSV file created succesfully.");
} catch (Exception e) {
System.out.println("exception :" + e.getMessage());
}