001package jmri.jmrit.symbolicprog; 002 003import java.awt.event.ActionEvent; 004import java.io.File; 005import java.io.FileOutputStream; 006import java.io.IOException; 007import java.io.OutputStreamWriter; 008import java.nio.charset.StandardCharsets; 009import javax.swing.AbstractAction; 010import javax.swing.JFileChooser; 011import javax.swing.JFrame; 012import org.apache.commons.csv.CSVFormat; 013import org.apache.commons.csv.CSVPrinter; 014import org.slf4j.Logger; 015import org.slf4j.LoggerFactory; 016 017/** 018 * Action to export the CV values to a Comma Separated Variable (CSV) data file. 019 * 020 * @author Bob Jacobsen Copyright (C) 2003 021 */ 022public class CsvExportAction extends AbstractAction { 023 024 public CsvExportAction(String actionName, CvTableModel pModel, JFrame pParent) { 025 super(actionName); 026 mModel = pModel; 027 mParent = pParent; 028 } 029 030 JFileChooser fileChooser; 031 JFrame mParent; 032 033 /** 034 * CvTableModel to load 035 */ 036 CvTableModel mModel; 037 038 @Override 039 public void actionPerformed(ActionEvent e) { 040 041 if (fileChooser == null) { 042 fileChooser = new jmri.util.swing.JmriJFileChooser(); 043 } 044 045 int retVal = fileChooser.showSaveDialog(mParent); 046 047 if (retVal == JFileChooser.APPROVE_OPTION) { 048 File file = fileChooser.getSelectedFile(); 049 if (log.isDebugEnabled()) { 050 log.debug("start to export to CSV file {}", file); 051 } 052 053 try (CSVPrinter str = new CSVPrinter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), CSVFormat.DEFAULT)) { 054 str.printRecord("CV", "value"); 055 for (int i = 0; i < mModel.getRowCount(); i++) { 056 CvValue cv = mModel.getCvByRow(i); 057 if (isWritable(cv)) { 058 String num = cv.number(); 059 int value = cv.getValue(); 060 str.printRecord(num, value); 061 } 062 } 063 str.flush(); 064 } catch (IOException ex) { 065 log.error("Error writing file", ex); 066 } 067 } 068 } 069 070 /** 071 * Decide whether a given CV should be written out. 072 * @param cv CV to be checked 073 * @return true if CV should be included in output file. 074 */ 075 protected boolean isWritable(CvValue cv) { 076 return true; 077 } 078 079 080 private final static Logger log = LoggerFactory.getLogger(CsvExportAction.class); 081}