Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package csv.to.sql.parser; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileNameExtensionFilter; import org.apache.commons.io.LineIterator; /** * * @author josemunoz */ public class mainMenu extends javax.swing.JFrame { private boolean fileSelected, resultOk; private File selectedFile; /** * Creates new form mainMenu */ public mainMenu() { initComponents(); this.fileSelected = false; this.resultOk = false; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnOpenFile = new javax.swing.JButton(); btnParse = new javax.swing.JButton(); lblTitulo = new javax.swing.JLabel(); lblFile = new javax.swing.JLabel(); btnHelp = new javax.swing.JButton(); jSeparator1 = new javax.swing.JSeparator(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); btnOpenFile.setText("Open File"); btnOpenFile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOpenFileActionPerformed(evt); } }); btnParse.setText("Parse"); btnParse.setEnabled(false); btnParse.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnParseActionPerformed(evt); } }); lblTitulo.setText("Select a CSV file to parse!"); lblFile.setText("No File Selected!"); btnHelp.setText("Help"); btnHelp.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnHelpActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(46, 46, 46) .addComponent(lblTitulo)) .addGroup(layout.createSequentialGroup().addGap(15, 15, 15) .addComponent(btnOpenFile))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 112, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnHelp).addComponent(btnParse))) .addGroup(layout.createSequentialGroup().addGap(143, 143, 143).addComponent(lblFile) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap().addComponent(jSeparator1))) .addContainerGap())); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(25, 25, 25).addComponent(lblTitulo)) .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(btnHelp))) .addGap(27, 27, 27).addComponent(lblFile) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnOpenFile).addComponent(btnParse)) .addGap(22, 22, 22))); pack(); }// </editor-fold>//GEN-END:initComponents private void btnOpenFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenFileActionPerformed // TODO add your handling code here: JFileChooser myFile = new JFileChooser(); myFile.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv")); myFile.showOpenDialog(this); this.selectedFile = myFile.getSelectedFile(); if (this.selectedFile.exists()) { this.fileSelected = true; this.lblFile.setText(this.selectedFile.getName()); this.btnOpenFile.setEnabled(false); this.btnParse.setEnabled(true); } else { JOptionPane.showInternalMessageDialog(this, "The file doesn't exists!"); } }//GEN-LAST:event_btnOpenFileActionPerformed private void btnParseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnParseActionPerformed // TODO add your handling code here: String filePath = this.selectedFile.getPath(); filePath = filePath.replace(".csv", " "); File resultFile = new File(this.validFilePath(filePath + "csvTo.sql")); BufferedReader br = null; BufferedWriter bw = null; try { if (resultFile.createNewFile()) { String currLine = null; br = new BufferedReader(new FileReader(this.selectedFile)); bw = new BufferedWriter(new FileWriter(resultFile)); bw.write("INSERT INTO " + this.selectedFile.getName().replace(".csv", "") + " " + this.formatFields(br.readLine()).replace('"', '`') + " VALUES\n"); LineIterator it = new LineIterator(br); boolean lineStatus = it.hasNext(); while (lineStatus) { currLine = it.next(); bw.write(this.formatFields(currLine) + ((lineStatus = it.hasNext()) ? ",\n" : ";")); } this.resultOk = true; } } catch (IOException ex) { this.resultOk = false; System.out.println("Error al crear el archivo: " + ex.getMessage()); } finally { try { if (br != null & bw != null) { br.close(); bw.close(); } } catch (IOException ex) { Logger.getLogger(mainMenu.class.getName()).log(Level.SEVERE, null, ex); } JOptionPane.showMessageDialog(this, "Parse " + (this.resultOk ? "Successful!" : "Error!")); this.selectedFile = null; this.lblFile.setText("No File Selected!"); this.btnOpenFile.setEnabled(true); this.btnParse.setEnabled(false); } }//GEN-LAST:event_btnParseActionPerformed private String validFilePath(String path) { return this.validFilePath(path, 0); } private String validFilePath(String path, int index) { if (new File(path).exists()) { int count = 4; while ((index /= 10) > 0) { count += 1; } path = path.substring(0, path.length() - (count)).concat(" " + index + ".sql"); return this.validFilePath(path, index + 1); } return path; } private String formatFields(String line) { if (line.contains(",")) { String[] Data = null; StringBuilder resultado = new StringBuilder(); resultado.append("("); Data = line.split(","); for (String currLine : Data) { resultado.append(currLine); resultado.append(","); } resultado.deleteCharAt(resultado.length() - 1).append(")"); return resultado.toString(); } return line; } private void btnHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHelpActionPerformed // TODO add your handling code here: JOptionPane.showMessageDialog(this, "Hello! Thank you for using csv to sql parser v0.1.2\nHere are a few instructions on how to use this tool:\n1: name your CSV file to the target sql table\n2: Make sure the first row in the CSV file has the column names\n\tof the target SQL table and wrap each one on quote(\") tags"); }//GEN-LAST:event_btnHelpActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(mainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(mainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(mainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(mainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new mainMenu().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnHelp; private javax.swing.JButton btnOpenFile; private javax.swing.JButton btnParse; private javax.swing.JSeparator jSeparator1; private javax.swing.JLabel lblFile; private javax.swing.JLabel lblTitulo; // End of variables declaration//GEN-END:variables }