java JFileChooser选择文件和保存文件

 

//文件过滤器
import
java.io.File; import javax.swing.filechooser.FileFilter; public class MyFilter extends FileFilter{ private String[] filterString = null; public MyFilter(String[] filStrings){ this.filterString = filStrings; } public boolean accept(File file){ if(file.isDirectory()) return true; for(int i=0; i<filterString.length; ++i) if(file.getName().endsWith(filterString[i])) return true; /* 返回要显示的文件类型 */ /* * File.isDirectory()测试此抽象路径名表示的文件是否是一个目录 */ return false; } public String getDescription() { String ss = ""; for(int i=0; i<filterString.length; ++i) ss += " *" + filterString[i]; return("Txt Files(" + ss + ")"); //返回显示文件类型的描述 } }
//文件的选择
          JFileChooser jfc = new JFileChooser(); //设置文件的过滤器 String[] filterString = {".cpp", ".c"}; MyFilter filter = new MyFilter(filterString); //获取jar包位置,设置JFileChooser当前路径 String jarFilePath = Main.class.getProtectionDomain().getCodeSource().getLocation().getFile(); try { jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } jfc.setCurrentDirectory(new File(jarFilePath)); jfc.setFileFilter(filter); jfc.showOpenDialog(null); File fl = jfc.getSelectedFile(); if(fl != null){ String code = ""; try { BufferedReader br = new BufferedReader(new FileReader(fl)); String newLine = null; boolean flag = true; while((newLine=br.readLine()) != null){ } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }

 

//文件的保存
            JFileChooser jfc = new JFileChooser(); String[] filterString = {".txt"}; //设置文件的过滤器 MyFilter filter = new MyFilter(filterString); //获取jar包位置,设置JFileChooser当前路径 String jarFilePath = LexicalAnalyzer.class.getProtectionDomain().getCodeSource().getLocation().getFile(); try { jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } jfc.setCurrentDirectory(new File(jarFilePath)); jfc.setFileFilter(filter); jfc.showSaveDialog(null); File fl = jfc.getSelectedFile(); OutputStreamWriter osw; try { osw = new OutputStreamWriter(new FileOutputStream(fl)); String text = textPane.getText(); osw.write(text, 0, text.length()); osw.flush(); osw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

 

你可能感兴趣的:(JFileChooser)