source: src/main/java/weka/gui/SaveBuffer.java @ 14

Last change on this file since 14 was 4, checked in by gnappo, 14 years ago

Import di weka.

File size: 5.7 KB
Line 
1/*
2 *    This program is free software; you can redistribute it and/or modify
3 *    it under the terms of the GNU General Public License as published by
4 *    the Free Software Foundation; either version 2 of the License, or
5 *    (at your option) any later version.
6 *
7 *    This program is distributed in the hope that it will be useful,
8 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 *    GNU General Public License for more details.
11 *
12 *    You should have received a copy of the GNU General Public License
13 *    along with this program; if not, write to the Free Software
14 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
15 */
16
17/*
18 *    SaveBuffer.java
19 *    Copyright (C) 2000 University of Waikato, Hamilton, New Zealand
20 *
21 */
22
23package weka.gui;
24
25import weka.gui.Logger;
26
27import java.io.File;
28import java.io.FileWriter;
29import java.io.Writer;
30import java.io.BufferedWriter;
31import java.io.PrintWriter;
32
33import java.awt.Component;
34import javax.swing.JFileChooser;
35import javax.swing.JButton;
36import javax.swing.JOptionPane;
37import javax.swing.JDialog;
38
39/**
40 * This class handles the saving of StringBuffers to files. It will pop
41 * up a file chooser allowing the user to select a destination file. If
42 * the file exists, the user is prompted for the correct course of action,
43 * ie. overwriting, appending, selecting a new filename or canceling.
44 *
45 * @author Mark Hall (mhall@cs.waikato.ac.nz)
46 * @version $Revision 1.0 $
47 */
48public class SaveBuffer {
49
50  /** The Logger to send messages to */
51  private Logger m_Log;
52
53  /** The parent component requesting the save */
54  private Component m_parentComponent;
55
56  /** Last directory selected from the file chooser */
57  private String m_lastvisitedDirectory=null;
58
59  /**
60   * Constructor
61   * @param log the logger to send messages to
62   * @param parent the parent component will be requesting a save
63   */
64  public SaveBuffer(Logger log, Component parent) {
65    m_Log = log;
66    m_parentComponent = parent;
67  }
68
69  /**
70   * Save a buffer
71   * @param buf the buffer to save
72   * @return true if the save is completed succesfully
73   */
74  public boolean save(StringBuffer buf) {
75    if (buf != null) {
76      JFileChooser fileChooser;
77      if (m_lastvisitedDirectory == null) {
78        fileChooser = new JFileChooser(
79                      new File(System.getProperty("user.dir")));
80      } else {
81        fileChooser = new JFileChooser(m_lastvisitedDirectory);
82      }
83
84      fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
85      int returnVal = fileChooser.showSaveDialog(m_parentComponent);
86      if (returnVal == JFileChooser.APPROVE_OPTION) {
87        File sFile = fileChooser.getSelectedFile();
88        m_lastvisitedDirectory = sFile.getPath();
89
90        if (sFile.exists()) {
91          Object [] options = new String[4];
92          options[0] = "Append";
93          options[1] = "Overwrite";
94          options[2] = "Choose new name";
95          options[3] = "Cancel";
96       
97          JOptionPane jop = new JOptionPane("File exists",
98                                             JOptionPane.QUESTION_MESSAGE,
99                                            1,
100                                            null,
101                                            options);
102          JDialog dialog = jop.createDialog(m_parentComponent, "File query");
103          dialog.setVisible(true);
104          Object selectedValue = jop.getValue();
105          if (selectedValue == null) {
106          } else {
107            for(int i=0; i<4; i++) {
108              if(options[i].equals(selectedValue)) {
109                switch (i) {
110                  // append
111                case 0:
112                  return saveOverwriteAppend(buf, sFile, true);
113                  // overwrite
114                case 1: 
115                  return saveOverwriteAppend(buf, sFile, false);
116                  // pick new name
117                case 2:
118                  return save(buf);
119                  // cancel
120                case 3: break;
121                }
122              }
123            }
124          }
125        } else {
126          saveOverwriteAppend(buf, sFile, false); // file does not exist
127        }
128      } else {
129        return false; // file save canceled
130      }
131    }
132    return false; // buffer null
133  }
134
135  /**
136   * Saves the provided buffer to the specified file
137   * @param buf the buffer to save
138   * @param sFile the file to save to
139   * @param append true if buffer is to be appended to file
140   * @return true if save is succesful
141   */
142  private boolean saveOverwriteAppend(StringBuffer buf, 
143                                      File sFile,
144                                      boolean append) {
145
146    try {
147      String path = sFile.getPath();
148      if (m_Log != null) {
149        if (append) {
150          m_Log.statusMessage("Appending to file...");
151        } else {
152          m_Log.statusMessage("Saving to file...");
153        }
154      }
155      PrintWriter out
156        = new PrintWriter(new BufferedWriter(
157                          new FileWriter(path, append)));
158      out.write(buf.toString(),0,buf.toString().length());
159      out.close();
160      if (m_Log != null) {
161        m_Log.statusMessage("OK");
162      }
163    } catch (Exception ex) {
164      ex.printStackTrace();
165      if (m_Log != null) {
166        m_Log.logMessage(ex.getMessage());
167      }
168      return false;
169    }
170
171    return true;
172  }
173
174  /**
175   * Main method for testing this class
176   */
177  public static void main(String [] args) {
178     try {
179       final javax.swing.JFrame jf =
180         new javax.swing.JFrame("SaveBuffer test");
181      jf.getContentPane().setLayout(new java.awt.BorderLayout());
182      weka.gui.LogPanel lp = new weka.gui.LogPanel();
183      javax.swing.JButton jb = new javax.swing.JButton("Save");
184      jf.getContentPane().add(jb,java.awt.BorderLayout.SOUTH);
185      jf.getContentPane().add(lp, java.awt.BorderLayout.CENTER);
186      final SaveBuffer svb = new SaveBuffer(lp, jf);
187      jb.addActionListener(new java.awt.event.ActionListener() {
188          public void actionPerformed(java.awt.event.ActionEvent e) {
189            svb.save(new StringBuffer("A bit of test text"));
190          }
191        });
192
193      jf.addWindowListener(new java.awt.event.WindowAdapter() {
194          public void windowClosing(java.awt.event.WindowEvent e) {
195            jf.dispose();
196            System.exit(0);
197          }
198        });
199      jf.pack();
200      jf.setVisible(true);
201     } catch (Exception ex) {
202       ex.printStackTrace();
203       System.err.println(ex.getMessage());
204     }
205  }
206}
Note: See TracBrowser for help on using the repository browser.