1 7 package org.ejtools.util; 8 9 import java.io.File ; 10 import java.text.MessageFormat ; 11 import java.util.ResourceBundle ; 12 13 import javax.swing.JFileChooser ; 14 import javax.swing.JOptionPane ; 15 import javax.swing.filechooser.FileFilter ; 16 17 24 public class FileTools 25 { 26 27 private static ResourceBundle resources = ResourceBundle.getBundle("org.ejtools.util.Resources"); 28 29 30 31 protected FileTools() { } 32 33 34 45 public static File selectFile(String title, String approveText, int type, SimpleFileFilter filter) 46 { 47 File selectedFile = null; 48 49 SecurityManager s = System.getSecurityManager(); 51 System.setSecurityManager(null); 52 53 JFileChooser chooser = new JFileChooser (System.getProperty("user.dir")); 55 chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); 56 chooser.setDialogTitle(title); 57 chooser.setDialogType(type); 58 chooser.setFileFilter(filter); 59 60 int returnVal = chooser.showDialog(null, approveText); 61 System.setSecurityManager(s); 62 if (returnVal == JFileChooser.APPROVE_OPTION) 63 { 64 selectedFile = chooser.getSelectedFile(); 65 } 66 67 if (selectedFile != null) 68 { 69 if (!filter.accept(selectedFile)) 71 { 72 selectedFile = new File (selectedFile.getName() + filter.getExtension()); 73 } 74 75 if ((type == JFileChooser.SAVE_DIALOG) && (selectedFile.exists())) 77 { 78 int ret = JOptionPane.showConfirmDialog(null, MessageFormat.format(resources.getString("file.dialog.overwrite.text"), new Object []{selectedFile.getName()})); 79 if (ret != JOptionPane.OK_OPTION) 80 { 81 selectedFile = null; 82 } 83 } 84 } 85 86 return selectedFile; 87 } 88 89 90 96 protected static class SimpleFileFilter extends FileFilter 97 { 98 private String description; 99 private String extension; 100 101 102 108 public SimpleFileFilter(String extension, String description) 109 { 110 this.extension = extension; 111 this.description = description; 112 } 113 114 115 121 public boolean accept(File file) 122 { 123 return file.getName().endsWith(this.extension); 124 } 125 126 127 132 public String getDescription() 133 { 134 return this.description; 135 } 136 137 138 143 public String getExtension() 144 { 145 return this.extension; 146 } 147 } 148 } 149 | Popular Tags |