Write CSV File in Java

In Java, you can use the classes java.io.FileWriter and java.io.BufferedWriter to write data to a CSV file. Here is an example code:

import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class WriteCSVFile {
    public static void main(String[] args) {
        String csvFile = "data.csv";  // CSV文件路径

        try {
            FileWriter fw = new FileWriter(csvFile);
            BufferedWriter bw = new BufferedWriter(fw);

            // 写入CSV文件的数据
            bw.write("Name, Age, City");
            bw.newLine();
            bw.write("John, 25, New York");
            bw.newLine();
            bw.write("Jane, 30, Los Angeles");

            bw.close();
            fw.close();

            System.out.println("Data has been written to " + csvFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above code, start by creating a FileWriter object to write to the file. Next, use the write and newLine methods provided by the BufferedWriter class to write the data line by line to the CSV file. Finally, close both the BufferedWriter and FileWriter objects.

After running the code, the data will be written into the specified CSV file.

bannerAds