Wednesday, June 26, 2013

Structure for write file in java

// declare JFileChooser
JFileChooser fileChooser = new JFileChooser();
 
// let the user choose the destination file
if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
    // indicates whether the user still wants to export the settings
    boolean doExport = true;
 
    // indicates whether to override an already existing file
    boolean overrideExistingFile = false;
 
    // get destination file
    File destinationFile = new File(fileChooser.getSelectedFile().getAbsolutePath());
 
    // check if file already exists
    while (doExport && destinationFile.exists() && !overrideExistingFile) {
        // let the user decide whether to override the existing file
        overrideExistingFile = (JOptionPane.showConfirmDialog(this, "Replace file?", "Export Settings", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION);
 
        // let the user choose another file if the existing file shall not be overridden
        if (!overrideExistingFile) {
            if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                // get new destination file
                destinationFile = new File(fileChooser.getSelectedFile().getAbsolutePath());
            } else {
                // seems like the user does not want to export the settings any longer
                doExport = false;
            }
        }
    }
 
    // perform the actual export
    if (doExport) {
        ExportTable(destinationFile);
    }
}
 
 
 
 public void ExportTable(File file)throws Exception
    {
        FileWriter writer = new FileWriter(file);
        BufferedWriter bfw = new BufferedWriter(writer);       
        for(int i = 0 ; i < table.getColumnCount() ; i++)
        {
            bfw.write(table.getColumnName(i)+" ");
        }
        bfw.write("\n");
        for (int i = 0 ; i < table.getRowCount(); i++)
        {
            for(int j = 0 ; j < table.getColumnCount();j++)
            {
                bfw.write((String)(table.getValueAt(i,j))+"\t");
            }
             bfw.write("\n");
        }
        bfw.close();
        writer.close();
    }

No comments:

Post a Comment