使用原生Java代码生成可执行Jar包(三)
ize() == 0) {
14 JOptionPane.showMessageDialog(this, "未选择文件", "错误", JOptionPane.ERROR_MESSAGE);
15 return;
16 } else if(cobMainClass.getSelectedItem() == null) {
17 JOptionPane.showMessageDialog(this, "未选择启动类", "错误", JOptionPane.ERROR_MESSAGE);
18 return;
19 }
20 // 打包
21 int result = jfcSave.showSaveDialog(this);
22 if(result == JFileChooser.APPROVE_OPTION) {
23 try {
24 // 清单文件
25 Manifest man = new Manifest();
26 // 版本和启动类路径必要
27 man.getMainAttributes().putValue(Name.MANIFEST_VERSION.toString(), "1.0");
28 man.getMainAttributes().putValue(Name.MAIN_CLASS.toString(), cobMainClass.getSelectedItem().toString());
29 // Class-Path一定不要,除非能保证将引用类(即import的类)都联合打包了
30 JarOutputStream jos = new JarOutputStream(new FileOutputStream(jfcSave.getSelectedFile()), man);
31 jos.setLevel(Deflater.BEST_COMPRESSION);
32 BufferedInputStream bis = null;
33 byte[] cache = new byte[1024];
34 StringBuffer config = new StringBuffer();
35 for(String name : filePaths.keySet()) {
36 bis = new BufferedInputStream(new FileInputStream(filePaths.get(name)), 1024);
37 config.append(name).append('=').append(bis.available()).append('\n');
38 jos.putNextEntry(new JarEntry(name));
39 int count;
40 while((count = bis.read(cache, 0, 1024)) != -1)
41 jos.write(cache, 0, count);
42 jos.closeEntry();
43 bis.close();
44 }
45 jos.flush();
46 jos.close();
47 JOptionPane.showMessageDialog(this, "导出成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
48 System.exit(0);
49 } catch(Exception ex) {
50 JOptionPane.showMessageDialog(this, ex.getMessage(), "异常", JOptionPane.ERROR_MESSAGE);
51 System.exit(1);
52 }
53 }
54 }
55
56 }