使用JFileChooser选择fileextension

时间:2014-04-19 01:36:42

标签: java file filter jfilechooser

我正在尝试做一些非常基本的事情:

保存文件时,JFileChooser应该有关于我要保存文件格式的选项,如果没有选择,则默认情况下应保存为.txt。

人们会想到一个简单的事情。 这是我到目前为止所得到的: 一个完全工作的读写类,它接收文件路径和文件名,并创建该文件。 带有JFileChooser的{​​{1}}也已准备就绪,但我无法弄清楚如何实际使用这些信息,用户选择了过滤器...

这是选择器的外观。

File Filter

如上所述,有两个问题:

- 如何使用所选过滤器中的信息指定文件应具有的扩展名。

- 如果在文件名字段中没有声明扩展且没有选择过滤器,我可以设置.txt作为默认值吗?

基本上我所要求的就是完成基本或预期的行为。

如果有人可以提供帮助,那会很棒。 ther Haeri

1 个答案:

答案 0 :(得分:0)

我对Stackoverflow感到很失望......好吧..这是修改后的FileChooser。希望我能帮助别人。 PS:我注意到,在Filechooser中包装write函数不是一个好主意。所以最好的办法是使用.getFullName()获取名称+扩展名;方法并将名称发送到写入函数。

import java.io.File;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

public class MyFileChooser extends JFileChooser {

public MyFileChooser(String path, String defName) {
    super(path);
    FileFilter txtType = new FileNameExtensionFilter("Text File (.txt)", "txt");
    FileFilter htmlType = new FileNameExtensionFilter("HTML File (.HTML)", "HTML");
    this.addChoosableFileFilter(txtType);
    this.addChoosableFileFilter(htmlType);
    this.setSelectedFile(new File(defName));
    Action details = this.getActionMap().get("viewTypeDetails");
    details.actionPerformed(null);
}

public String getFullName() {
    String[] temp;
    String extens, temp2, temp3;

    temp3 = this.getSelectedFile().getName();
    try {
        temp = this.getFileFilter().getDescription().split("[\\(||\\)]");

        if (temp3.endsWith(temp[1])) {
            return temp3;
        }else{
            return temp3 + temp[1];
        }
    }catch (Exception e){

        try {
            temp2 = this.getSelectedFile().getName();
            extens = temp2.substring(temp2.lastIndexOf('.')).trim();

            return temp3;
        }catch (Exception ee) {
            return temp3 + ".txt";
        }               
    }
}


public String getFolderPath() {
    String inputName = this.getSelectedFile().getName();
    String fullPath = this.getSelectedFile().getPath();
    String result = fullPath.replaceAll(""+ inputName + "$", "");

    return result;
}

}