zoukankan      html  css  js  c++  java
  • 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(); }
  • 相关阅读:
    设计模式之结构型(6)-享元模式(Flyweight)
    设计模式之结构型(7)-代理模式(Proxy)
    设计模式之行为型(1)-职责链模式(Chain)
    设计模式之行为型(2)-命令模式(Command)
    设计模式之行为型(3)-解释器模式(Interpreter)
    设计模式之行为型(4)-迭代器模式(Iterator)
    设计模式之行为型(5)-中介者模式(Mediator)
    设计模式之行为型(6)-备忘录模式(Memento)
    设计模式之行为型(7)-观察者模式(Observer)
    设计模式之行为型(8)-状态模式(State)
  • 原文地址:https://www.cnblogs.com/hujunzheng/p/4399248.html
Copyright © 2011-2022 走看看