在Java中,可以使用以下方法將數(shù)據(jù)寫入CSV文件:
BufferedWriter
將數(shù)據(jù)寫入文件。String filename = "example.csv";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
// 寫入數(shù)據(jù)
writer.write("Header 1,Header 2,Header 3"); // 寫入標(biāo)題行
writer.newLine(); // 寫入換行符
writer.write("Data 1,Data 2,Data 3"); // 寫入數(shù)據(jù)行
writer.newLine(); // 寫入換行符
} catch (IOException e) {
e.printStackTrace();
}
opencsv
進(jìn)行寫入操作。首先需要添加opencsv
庫的依賴:<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.5.2</version>
</dependency>
然后使用以下代碼寫入數(shù)據(jù):
String filename = "example.csv";
try (CSVWriter writer = new CSVWriter(new FileWriter(filename))) {
// 寫入數(shù)據(jù)
String[] header = {"Header 1", "Header 2", "Header 3"};
writer.writeNext(header); // 寫入標(biāo)題行
String[] data = {"Data 1", "Data 2", "Data 3"};
writer.writeNext(data); // 寫入數(shù)據(jù)行
} catch (IOException e) {
e.printStackTrace();
}
注意:使用opencsv
庫時(shí),需要引入CSVWriter
類,并使用writeNext()
方法寫入每一行的數(shù)據(jù)。