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