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

Ale*_*ich 2 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();

        }

    } 
Run Code Online (Sandbox Code Playgroud)

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");
    }

}
Run Code Online (Sandbox Code Playgroud)

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我有两个主要课程.我添加TestGUI.java到清单中,因此GUI将显示出来.一旦用户单击该按钮,我希望我的程序创建一个由Main.java和组成的Runnable JAR Selenium.java.

但是,我得到一个错误null pointer exceptionint compilationResult = compiler.run(null, null, null, file1ToCompile, file2ToCompile);

我怎样才能做到这一点?

Sio*_*733 7

NullPointerException最有可能因为你使用的是JRE而不是JDK.下载 JDK并将其添加到buildpath.

其次,您只是编译文件.然后,您需要创建一个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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

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