jFileChooser showSaveDialog 保存文件

来源:互联网 发布:订货系统源码 编辑:程序博客网 时间:2024/03/29 20:33
posted by David Chen at October 30, 2007 7:22 PM
jFileChooser showSaveDialog 保存文件
使用 swing的文件对话来保存的话,必须要注意几个地方, chooser.getSelectedFile(); 这个函数返回的
是对话框选中的文件,但如果对话框类型是showSaveDialog的话,那么这里返回的值是你要保存的文件,这个文件可能存在,可能不存在,就是你在对话框中输入的文件名了,
既然知道了文件,如果不存在,就新建一个,然后向文件写入数据,这样就可以实现保存了.不要以为chooser会
自动帮你读数据并存进去,这些都要自已用代码实现.
下面这个列子是将jTextPanel中数据保存到 html文件中.
[java] view plaincopy
  1. public void mouseClicked(MouseEvent arg0) { javax.swing.JFileChooser jfc = new javax.swing.JFileChooser() {  public String paramString() {   return "drhdrhdrh";  } };// 这里新建一个chooser    FileFilter filter = new FileFilter() {     public boolean accept(File f) {      return f.isDirectory() || (f.isFile() && (    f.getName().endsWith(".htm")    || f.getName().endsWith(".HTM")    || f.getName().endsWith(".html")    || f.getName().endsWith(".HTML")    )); // 新建一个文件类型过滤器     }     public String getDescription() {      return "保存为HTML文件格式";     }    };    jfc.setFileFilter(filter);    int i = jfc.showSaveDialog(jContentPane); // 打开保存文件对话框        String fname = null;    if(i == javax.swing.JFileChooser.APPROVE_OPTION) {     File f = jfc.getSelectedFile();// 注意这里,和下面一句, 如果这里并没有选取中任何的文件,下面的jfc.getName(f)将会返回手输入的文件名     fname = jfc.getName(f);     if(fname != null && fname.trim().length()>0) {      if(fname.endsWith(".htm") || fname.endsWith(".HTM") || fname.endsWith(".html") || fname.endsWith(".HTML"))       ;      else {       fname = fname.concat(".htm");      }     }     if(f.isFile())      fname = f.getName();     f = jfc.getCurrentDirectory();// 取得要保存的文件的目录,其实getSelectedFile();已经包括了文件路径,这里这样是让大家更易了解          f = new File(f.getPath().concat(File.separator).concat(fname));     if(f.exists()) {      i = javax.swing.JOptionPane.showConfirmDialog(jContentPane, "该文件已经存在,确定要覆盖吗?");      if(i == javax.swing.JOptionPane.YES_OPTION)       ;      else       return ;     }     try {      f.createNewFile();      java.io.FileWriter fw = new java.io.FileWriter(f);      fw.write(getJtp_html().getText());      fw.close();// 向要保存的文件写数据     } catch(Exception ex) {      javax.swing.JOptionPane.showMessageDialog(jContentPane, "出错:" + ex.getMessage());      return ;     }    }}  
  2. Labels: java, swing  
0 0
原创粉丝点击