/Users/lyon/j4p/src/net/rmi/rmiSynth/lex/FileSaver.java
|
1 /**
2 * Class FileSaver
3 * Shows a dialog for saving a file and eventually saves it
4 */
5 package net.rmi.rmiSynth.lex;
6
7 import javax.swing.JOptionPane;
8 import java.awt.FileDialog;
9 import java.awt.Frame;
10 import java.io.BufferedWriter;
11 import java.io.File;
12 import java.io.FileWriter;
13
14 public class FileSaver {
15 /**
16 * Method createFile Promts user for a
17 * filename and saves the file
18 *
19 * @param source Future file content
20 * @param fileName Name of the file
21 */
22 public void createFile(String source,
23 String fileName) {
24 String fn = getSaveFileName(
25 "save file as", fileName); //Show dialog
26 //If no name is specified show warning and get out
27 if (fn == null) {
28 JOptionPane.showMessageDialog
29 (null,
30 "No filename is specified! operation aborted.",
31 "Wait a second",
32 JOptionPane.INFORMATION_MESSAGE);
33 return;
34 }
35 //Create new file <fn>
36 File f = new File(fn);
37 BufferedWriter bw = null;
38 // Open file
39 try {
40 bw =
41 new BufferedWriter(new FileWriter(f));
42 } catch (Exception e) {
43 }
44 //Write
45 try {
46 bw.write(source);
47 } catch (Exception e) {
48 }
49 //Close
50 try {
51 bw.close();
52 } catch (Exception e) {
53 }
54 }
55
56 /**
57 * Method getSaveFileName Shows Save File
58 * dialog
59 *
60 * @param prompt Prompt to show in title
61 * bar
62 * @param fileName Name of the file
63 * @return fn File name that user typed in
64 */
65 public String getSaveFileName(String prompt,
66 String fileName) {
67 //Prepare dialog
68 FileDialog fd = new FileDialog(
69 new Frame(),
70 prompt,
71 FileDialog.SAVE);
72 fd.setFile(fileName + ".java");
73 //Show it
74 fd.setVisible(true);
75 fd.setVisible(false);
76 //Get file name
77 String fn = fd.getDirectory() +
78 fd.getFile();
79 if (fd.getFile() == null) return null;
80 return fn;
81 }
82 }