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 + ")"); //返回显示文件类型的描述 } }
java JFileChooser选择文件和保存文件
java JFileChooser选择文件和保存文件
//文件的选择
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(); } }
java JFileChooser选择文件和保存文件

 

java JFileChooser选择文件和保存文件
//文件的保存
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(); }










本文转自 小眼儿 博客园博客,原文链接:http://www.cnblogs.com/hujunzheng/p/4399248.html,如需转载请自行联系原作者
上一篇:游戏设计必需遵循的八个原则(实例介绍)


下一篇:Andrew Ng机器学习公开课笔记 -- 支持向量机