|
| 1 | +import com.opencsv.CSVWriter; |
| 2 | +import java.io.FileWriter; |
| 3 | + |
| 4 | +public class CSVFileWritingInJava { |
| 5 | + public static void main(String[] args) { |
| 6 | + // Step 1: Path to the CSV file |
| 7 | + String filePath = "/Users/somesh/Java SE/JavaEvolution-Learning-Growing-Mastering/Section23JavaIOStreams/src/MyJAVA/data.csv"; |
| 8 | + |
| 9 | + try { |
| 10 | + // Step 2: FileWriter to write to the file |
| 11 | + FileWriter fileWriter = new FileWriter(filePath); |
| 12 | + |
| 13 | + // Step 3: CSVWriter from OpenCSV to write CSV rows |
| 14 | + CSVWriter csvWriter = new CSVWriter(fileWriter); |
| 15 | + |
| 16 | + // Step 4: Write header |
| 17 | + String[] header = { "Name", "Age", "City" }; |
| 18 | + csvWriter.writeNext(header); |
| 19 | + |
| 20 | + // Step 5: Write data rows |
| 21 | + String[] row1 = { "Alice", "25", "Bangalore" }; |
| 22 | + String[] row2 = { "Bob", "30", "Delhi" }; |
| 23 | + String[] row3 = { "Charlie", "22", "Mumbai" }; |
| 24 | + |
| 25 | + csvWriter.writeNext(row1); |
| 26 | + csvWriter.writeNext(row2); |
| 27 | + csvWriter.writeNext(row3); |
| 28 | + |
| 29 | + csvWriter.close(); |
| 30 | + |
| 31 | + } catch (Exception e) { |
| 32 | + System.out.println("Something went wrong while writing to the file."); |
| 33 | + e.printStackTrace(); |
| 34 | + } |
| 35 | + } |
| 36 | +} |
0 commit comments