以编程方式从GUI创建具有外部JAR的Runnable JAR?

时间:2014-02-07 23:35:13

标签: java java-compiler-api

我有一个简单的测试程序,只有一个按钮。当用户单击该按钮时,该程序应该创建一个Runnable JAR。 Runnable JAR是一个简单的程序,可以在Firefox中打开google.com。该计划有三个班级。


1)Main.java

 package test;

    public class Main {

        public static void main(String[] args) {

            Selenium.getGoogle();

        }

    } 

2)Selenium.Java

package test;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Selenium {

    public static void getGoogle () {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://google.com");
    }

}

3)TestGUI.java

package test;

import javax.swing.*;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class TestGUI extends JFrame implements ActionListener {

    private static final long serialVersionUID = 1L;

    public TestGUI() {

        setSize(200, 100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        /*
         * JButton.
         */
        JButton startButton = new JButton("Create Runnable JAR file ! ");
        add(startButton);
        startButton.addActionListener(this);
    }


    public static void main(String[] args) {
        new TestGUI();
    }


    public void actionPerformed(ActionEvent e) {
        System.out.println("The Button Works");
        String file1ToCompile = "test" + java.io.File.separator + "Main.java";

        String file2ToCompile = "test" + java.io.File.separator + "Selenium.java";

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        int compilationResult = compiler.run(null, null, null, file1ToCompile, file2ToCompile);

        if (compilationResult == 0) {

            System.out.println("Compilation is successful");

        } else {
            System.out.println("Compilation Failed");
        }
    }
}

我有两个主要课程。我将TestGUI.java添加到清单中,以便GUI显示出来。用户点击按钮后,我希望我的程序创建一个由Main.javaSelenium.java组成的Runnable JAR。

但是,null pointer exception

收到错误int compilationResult = compiler.run(null, null, null, file1ToCompile, file2ToCompile);

我该怎么做?

2 个答案:

答案 0 :(得分:7)

您最有可能得到NullPointerException,因为您使用的是JRE而不是JDK。 Download JDK并将其添加到构建路径中。

其次,您只是编译文件。然后,您需要创建一个jar文件并将.class文件添加到其中。重要的是它们在罐子里具有相同的包装结构。在罐子里你还需要:

清单文件

依赖的罐子

<强>类加载

清单文件描述了哪个类包含main方法和类路径信息。 由于显而易见的原因,还需要存在依赖的罐子(硒)。 需要一个类加载器来加载依赖jar中的类。以下是我的实施:

public void actionPerformed(ActionEvent e){
        System.out.println("The Button Works");
        String file1ToCompile = "src" + java.io.File.separator + "test" + java.io.File.separator + "Main.java";
        String file2ToCompile = "src" + java.io.File.separator + "test" + java.io.File.separator + "Selenium.java";
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        int compilationResult = compiler.run(null, null, null, file1ToCompile, file2ToCompile);
        if (compilationResult == 0) {
            System.out.println("Compilation is successful");
        } else {
            System.out.println("Compilation Failed");
        }

        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        manifest.getMainAttributes().put(new Name("Rsrc-Class-Path"), "./ selenium-server-standalone-2.39.0.jar");
        manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, ".");
        manifest.getMainAttributes().put(new Name("Rsrc-Main-Class"), "test.Main");
        manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, "org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader");
        try{
            JarOutputStream target = new JarOutputStream(new FileOutputStream("output.jar"), manifest);
            add(new File("src" + java.io.File.separator + "test" + java.io.File.separator + "Main.class"), target);
            add(new File("src" + java.io.File.separator + "test" + java.io.File.separator + "Selenium.class"), target);
            add(new File("org"), target);
            add(new File("selenium-server-standalone-2.39.0.jar"), target);
            target.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    private void add(File source, JarOutputStream target) throws IOException
    {
        BufferedInputStream in = null;
        try
        {
            if (source.isDirectory())
            {
                String name = source.getPath().replace("\\", "/");
                if (!name.isEmpty())
                {
                    if (!name.endsWith("/"))
                        name += "/";
                    JarEntry entry = new JarEntry(name);
                    entry.setTime(source.lastModified());
                    target.putNextEntry(entry);
                    target.closeEntry();
                }
                for (File nestedFile: source.listFiles())
                    add(nestedFile, target);
                return;
            }

            JarEntry entry = null;

            if(source.getPath().contains("jarinjarloader")){
                entry = new JarEntry(source.getPath());
            }
            else if(source.getName().endsWith(".class")){
                entry = new JarEntry("test/"+source.getName());
            }else if(source.getName().endsWith(".classpath")){
                entry = new JarEntry(source.getName());
            }else if(source.getName().endsWith(".jar")){
                entry = new JarEntry(source.getName());
            }
            entry.setTime(source.lastModified());
            target.putNextEntry(entry);
            in = new BufferedInputStream(new FileInputStream(source));

            byte[] buffer = new byte[1024];
            while (true)
            {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        }
        finally
        {
            if (in != null)
                in.close();
        }
    }

我使用Eclipse的jarinjarloader作为我的类加载器,我通过在eclipse中创建一个可运行的jar并提取org文件夹并将其复制到我的项目目录中来获得。

enter image description here

这有一个小问题,但我怀疑我错过了一些小事。如果类加载器文件与jar在同一目录中,则output.jar将正常运行。我目前正在尝试修复此问题,以便它可以从jar中找到类加载器。

答案 1 :(得分:0)

Here是O.o终于找到它的答案!你只需要看到代码的最后一部分:

File folder = new File("C://Users//YourUser//YourWorkspace//YourProject//bin");
File[] files = folder.listFiles();
File file=new File("C://Users//YourUser//Desktop//Examples.jar");