首先是我们需要选择哪些字节码和文件需要打包到文件中,这个我们用JFileChooser来做,让用户选择,我做了一个窗体来让用户选择。
效果如下:
我们让浏览文件
系统,并选择需要打包的文件夹,然后计算出可以作为启动类的文件,通过下方的下拉让用户选择。
生成文件路径在确认按钮点击后弹出文件保存框让用户选择就好(也可以弹出输入框)。
代码如下:
Main
复制代码
1 package org.coderecord.commons.ejarmaker;
2
3 import java.awt.EventQueue;
4
5 import javax.swing.UIManager;
6 import javax.swing.UnsupportedLookAndFeelException;
7
8 public class Main {
9
10 public static void main(String[] args) {
11 try {
12 UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
13 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
14 e.printStackTrace();
15 }
16 EventQueue.invokeLater(new Runnable() {
17
18 @Override
19 public void run() {
20 new FrmMain().setVisible(true);
21 }
22 });
23 }
24
25 }
复制代码
FrmMain(只是界面代码,业务代码最后贴出)
1 @Override
2 public void actionPerformed(ActionEvent e) {
3 if(e.getSource() == btnBrowser) {
4 // 浏览
5 int result = jfcSelect.showOpenDialog(this);
6
7 // 选择了文件
8 if(result == JFileChooser.APPROVE_OPTION) {
9 for(File file : jfcSelect.getSelectedFiles())
11
12 // 整理选择的文件,去除重复项
13 removeDuplicateItems(userSelectedFiles);
14
15 // 重新计算选中文件
16 finalFiles.clear();
17 for(File file : userSelectedFiles)
18 addFileToList(file, finalFiles);
19
20 // 计算文件展示打包路径及展示路径
21 // 计算可启动类路径
22 // 展示到文本框中
23 cobMainClass.removeAllItems();
24 txtFiles.setText("");
25 File file,direc;
26 String filePath,direcPath;
27 Iterator itd,itf;
28 for(itd = userSelectedFiles.iterator(); itd.hasNext();) {
29 direc = itd.next();
30 direcPath = direc.getAbsolutePath();
31 for(itf = finalFiles.iterator(); itf.hasNext();) {
32 file = itf.next();
33 filePath = file.getAbsolutePath();
34 if(filePath.equalsIgnoreCase(direcPath)) {
35 txtFiles.append(file.getName() + "\n");
36 filePaths.put(file.getName(), file);
37 //fileNames.put(file.getName(), file.getName().endsWith(".class") file.getName().substring(0, file.getName().lastIndexOf('.')):file.getName());
38 if(file.getName().endsWith(".class"))
39 cobMainClass.addItem(file.getName().endsWith(".class") file.getName().substring(0, file.getName().lastIndexOf('.')):file.getName());
40 itf.remove();
41 } else if(filePath.startsWith(direcPath)) {
42 String nameTmp = filePath.substring(direcPath.lastIndexOf(File.separator) + 1).replace(File.separatorChar, '/');
43 filePaths.put(n