JFileChooser 选择目录,选择保存路径,并对保存文件类型进行更改:

时间:2021-07-07 07:12:30
 JFileChooser :

//选择目录
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = chooser.showOpenDialog(null);
String fname = chooser.getName(chooser.getSelectedFile());
if (result == JFileChooser.APPROVE_OPTION) {

String filePath = chooser.getSelectedFile().getPath();
System.out.println(filePath);
}

//保存文件:

JFileChooser fd = new JFileChooser();
HtmlFileFilter hff = new HtmlFileFilter();
fd.addChoosableFileFilter(hff);
fd.showSaveDialog(null);
File f = fd.getSelectedFile();
if (f != null){
System.out.println(f.getAbsolutePath() + ".html");
jTextField2.setText(f.getAbsolutePath() + ".html");
}

过滤器:

class HtmlFileFilter extends FileFilter {
public String getDescription() {
return "*.html(网页文件)";
}

public boolean accept(File file) {
String name = file.getName();
return name.toLowerCase().endsWith(".html");
}
}