当前位置: 移动技术网 > IT编程>开发语言>Java > Java文件选择对话框JFileChooser使用详解

Java文件选择对话框JFileChooser使用详解

2019年07月22日  | 移动技术网IT编程  | 我要评论
文件加密器,操作过程肯定涉及到文件选择器的使用,所以这里以文件加密器为例。下例为我自己写的一个文件加密器,没什么特别的加密算法,只为演示文件选择器jfilechooser的

文件加密器,操作过程肯定涉及到文件选择器的使用,所以这里以文件加密器为例。下例为我自己写的一个文件加密器,没什么特别的加密算法,只为演示文件选择器jfilechooser的使用。

加密器界面如图:

项目目录结构如图:

下面贴出各个文件的源代码:

mainform.java

package com.lidi;
import javax.swing.*;
import java.awt.*;
public class mainform extends jframe {
  /**
   * 构造界面
   * 
   * @author 1109030125
   */
  private static final long serialversionuid = 1l;
  /* 主窗体里面的若干元素 */
  private jframe mainform = new jframe("txt文件加密"); // 主窗体,标题为“txt文件加密”
  private jlabel label1 = new jlabel("请选择待加密或解密的文件:");
  private jlabel label2 = new jlabel("请选择加密或解密后的文件存放位置:");
  public static jtextfield sourcefile = new jtextfield(); // 选择待加密或解密文件路径的文本域
  public static jtextfield targetfile = new jtextfield(); // 选择加密或解密后文件路径的文本域
  public static jbutton buttonbrowsesource = new jbutton("浏览"); // 浏览按钮
  public static jbutton buttonbrowsetarget = new jbutton("浏览"); // 浏览按钮
  public static jbutton buttonencrypt = new jbutton("加密"); // 加密按钮
  public static jbutton buttondecrypt = new jbutton("解密"); // 解密按钮
  public mainform() {
    container container = mainform.getcontentpane();
    /* 设置主窗体属性 */
    mainform.setsize(400, 270);// 设置主窗体大小
    mainform.setdefaultcloseoperation(windowconstants.exit_on_close);// 设置主窗体关闭按钮样式
    mainform.setlocationrelativeto(null);// 设置居于屏幕中央
    mainform.setresizable(false);// 设置窗口不可缩放
    mainform.setlayout(null);
    mainform.setvisible(true);// 显示窗口
    /* 设置各元素位置布局 */
    label1.setbounds(30, 10, 300, 30);
    sourcefile.setbounds(50, 50, 200, 30);
    buttonbrowsesource.setbounds(270, 50, 60, 30);
    label2.setbounds(30, 90, 300, 30);
    targetfile.setbounds(50, 130, 200, 30);
    buttonbrowsetarget.setbounds(270, 130, 60, 30);
    buttonencrypt.setbounds(100, 180, 60, 30);
    buttondecrypt.setbounds(200, 180, 60, 30);
    /* 为各元素绑定事件监听器 */
    buttonbrowsesource.addactionlistener(new browseaction()); // 为源文件浏览按钮绑定监听器,点击该按钮调用文件选择窗口
    buttonbrowsetarget.addactionlistener(new browseaction()); // 为目标位置浏览按钮绑定监听器,点击该按钮调用文件选择窗口
    buttonencrypt.addactionlistener(new encryptaction()); // 为加密按钮绑定监听器,单击加密按钮会对源文件进行加密并输出到目标位置
    buttondecrypt.addactionlistener(new decryptaction()); // 为解密按钮绑定监听器,单击解密按钮会对源文件进行解密并输出到目标位置
    sourcefile.getdocument().adddocumentlistener(new textfieldaction());// 为源文件文本域绑定事件,如果文件是.txt类型,则禁用解密按钮;如果是.kcd文件,则禁用加密按钮。
    sourcefile.seteditable(false);// 设置源文件文本域不可手动修改
    targetfile.seteditable(false);// 设置目标位置文本域不可手动修改
    container.add(label1);
    container.add(label2);
    container.add(sourcefile);
    container.add(targetfile);
    container.add(buttonbrowsesource);
    container.add(buttonbrowsetarget);
    container.add(buttonencrypt);
    container.add(buttondecrypt);
  }
  public static void main(string args[]) {
    new mainform();
  }
}

browseaction.java

package com.lidi;
import java.awt.event.actionevent;
import java.awt.event.actionlistener;
import javax.swing.jfilechooser;
import javax.swing.filechooser.filenameextensionfilter;
public class browseaction implements actionlistener {
  @override
  public void actionperformed(actionevent e) {
    if (e.getsource().equals(mainform.buttonbrowsesource)) {
      jfilechooser fcdlg = new jfilechooser();
      fcdlg.setdialogtitle("请选择待加密或解密的文件...");
      filenameextensionfilter filter = new filenameextensionfilter(
          "文本文件(*.txt;*.kcd)", "txt", "kcd");
      fcdlg.setfilefilter(filter);
      int returnval = fcdlg.showopendialog(null);
      if (returnval == jfilechooser.approve_option) {
        string filepath = fcdlg.getselectedfile().getpath();
        mainform.sourcefile.settext(filepath);
      }
    } else if (e.getsource().equals(mainform.buttonbrowsetarget)) {
      jfilechooser fcdlg = new jfilechooser();
      fcdlg.setdialogtitle("请选择加密或解密后的文件存放目录");
      fcdlg.setfileselectionmode(jfilechooser.directories_only);
      int returnval = fcdlg.showopendialog(null);
      if (returnval == jfilechooser.approve_option) {
        string filepath = fcdlg.getselectedfile().getpath();
        mainform.targetfile.settext(filepath);
      }
    }
  }
}

encryptaction.java

package com.lidi;
import java.awt.event.actionevent;
import java.awt.event.actionlistener;
import java.io.file;
import java.io.filereader;
import java.io.filewriter;
import java.io.ioexception;
import javax.swing.joptionpane;
public class encryptaction implements actionlistener {
  @override
  public void actionperformed(actionevent e) {
    // todo auto-generated method stub
    if (mainform.sourcefile.gettext().isempty()) {
      joptionpane.showmessagedialog(null, "请选择待加密文件!");
    }
    else if (mainform.targetfile.gettext().isempty()) {
      joptionpane.showmessagedialog(null, "请选择加密后文件存放目录!");
    }
    else {
      string sourcepath = mainform.sourcefile.gettext();
      string targetpath = mainform.targetfile.gettext();
      file file = new file(sourcepath);
      string filename = file.getname();
      file dir = new file(targetpath);
      if (file.exists() && dir.isdirectory()) {
        file result = new file(getfinalfile(targetpath, filename));
        if (!result.exists()) {
          try {
            result.createnewfile();
          } catch (ioexception e1) {
            joptionpane.showmessagedialog(null,
                "目标文件创建失败,请检查目录是否为只读!");
          }
        }
        try {
          filereader fr = new filereader(file);
          filewriter fw = new filewriter(result);
          int ch = 0;
          while ((ch = fr.read()) != -1) {
            // system.out.print(encrypt(ch));
            fw.write(encrypt(ch));
          }
          fw.close();
          fr.close();
          joptionpane.showmessagedialog(null, "加密成功!");
        } catch (exception e1) {
          joptionpane.showmessagedialog(null, "未知错误!");
        }
      }
      else if (!file.exists()) {
        joptionpane.showmessagedialog(null, "待加密文件不存在!");
      } else {
        joptionpane.showmessagedialog(null, "加密后文件存放目录不存在!");
      }
    }
  }
  public char encrypt(int ch) {
    int x = ch + 1;
    return (char) (x);
  }
  public string getfinalfile(string targetpath, string filename) {
    int length = filename.length();
    string finalfilename = filename.substring(0, length - 4);
    string finalfile = targetpath + "\\" + finalfilename + ".kcd";
    return finalfile;
  }
}

decryptaction.java

package com.lidi;
import java.awt.event.actionevent;
import java.awt.event.actionlistener;
import java.io.file;
import java.io.filereader;
import java.io.filewriter;
import java.io.ioexception;
import javax.swing.joptionpane;
public class decryptaction implements actionlistener {
  @override
  public void actionperformed(actionevent e) {
    // todo auto-generated method stub
    if (mainform.sourcefile.gettext().isempty()) {
      joptionpane.showmessagedialog(null, "请选择待解密文件!");
    }
    else if (mainform.targetfile.gettext().isempty()) {
      joptionpane.showmessagedialog(null, "请选择解密后文件存放目录!");
    }
    else {
      string sourcepath = mainform.sourcefile.gettext();
      string targetpath = mainform.targetfile.gettext();
      file file = new file(sourcepath);
      string filename = file.getname();
      file dir = new file(targetpath);
      if (file.exists() && dir.isdirectory()) {
        file result = new file(getfinalfile(targetpath, filename));
        if (!result.exists()) {
          try {
            result.createnewfile();
          } catch (ioexception e1) {
            joptionpane.showmessagedialog(null,
                "目标文件创建失败,请检查目录是否为只读!");
          }
        }
        try {
          filereader fr = new filereader(file);
          filewriter fw = new filewriter(result);
          int ch = 0;
          while ((ch = fr.read()) != -1) {
            // system.out.print(encrypt(ch));
            fw.write(decrypt(ch));
          }
          fw.close();
          fr.close();
          joptionpane.showmessagedialog(null, "解密成功!");
        } catch (exception e1) {
          joptionpane.showmessagedialog(null, "未知错误!");
        }
      }
      else if (!file.exists()) {
        joptionpane.showmessagedialog(null, "待解密文件不存在!");
      } else {
        joptionpane.showmessagedialog(null, "解密后文件存放目录不存在!");
      }
    }
  }
  public char decrypt(int ch) {
    // double x = 0 - math.pow(ch, 2);
    int x = ch - 1;
    return (char) (x);
  }
  public string getfinalfile(string targetpath, string filename) {
    int length = filename.length();
    string finalfilename = filename.substring(0, length - 4);
    string finalfile = targetpath + "\\" + finalfilename + ".txt";
    return finalfile;
  }
}

textfieldaction.java

package com.lidi;
import javax.swing.event.documentevent;
import javax.swing.event.documentlistener;
public class textfieldaction implements documentlistener {
  @override
  public void insertupdate(documentevent e) {
    // todo auto-generated method stub
    buttonajust();
  }
  @override
  public void removeupdate(documentevent e) {
    // todo auto-generated method stub
    buttonajust();
  }
  @override
  public void changedupdate(documentevent e) {
    // todo auto-generated method stub
    buttonajust();
  }
  public void buttonajust() {
    string file = mainform.sourcefile.gettext();
    if (file.endswith("txt")) {
      mainform.buttondecrypt.setenabled(false);
      mainform.buttonencrypt.setenabled(true);
    }
    if (file.endswith("kcd")) {
      mainform.buttonencrypt.setenabled(false);
      mainform.buttondecrypt.setenabled(true);
    }
  }
}

以上所述就是本文的全部内容了,希望大家能够喜欢。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网