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(); }
  • 相关阅读:
    C++文件流类与文件流对象
    当java出现异常,应如何进行处理
    C语言函数的声明以及函数原型
    MySQL的create table as 与 like区别
    java中BigDecimal加减乘除基本用法
    项目小结
    自动化测试 如何快速提取Json数据
    Java Map 集合类在selenium自动化测试设计中的应用
    UFT对于PDF 文档的操作方法 VBS代码
    Selenium 自动化测试中对页面元素的value比较验证 java语言
  • 原文地址:https://www.cnblogs.com/hujunzheng/p/4399248.html
Copyright © 2011-2022 走看看