CSV (Comma Separated Values) is a file format having the values separated with a comma. Let us see how to write to CSV using a Java Program. Writing the file from BufferWriter is one of the ways to do it.
Write Data To CSV File in Java
import java.io.BufferedWriter;
import java.io.FileWriter;
public class WriteDataToCSVFile {
public static final String PATH = "C:\\Input\\Data.csv";
public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(PATH));
StringBuilder sb = new StringBuilder();
// Titles
sb.append("id");
sb.append(',');
sb.append("Name");
sb.append('\n');
// Content
sb.append("1");
sb.append(',');
sb.append("Krishna");
sb.append('\n');
sb.append("2");
sb.append(',');
sb.append("Aditya");
sb.append("\n");
writer.write(sb.toString());
// close writer
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
0 Comments