创建java进程以在当前jar中执行类

时间:2013-04-16 15:11:20

标签: java process jar classpath processbuilder

所以希望标题涵盖了jist,我知道有很多关于这类事情的帖子,我特别关注的问题是如何设置我当前运行的包含类的jar的类路径。

即我已经使用Maven程序集插件打包我的jar,其中所有依赖项都在内部展开。所以我只是尝试创建一个子进程来执行我的jar中存在的一个依赖类,从我的jar中。如果可能的话?

感谢下面的帖子,这是解决方案:

URL baseUrl = getClass().getProtectionDomain().getCodeSource().getLocation();
                String myPath = (new File(baseUrl.toURI())).getCanonicalPath();

ProcessBuilder pb = new ProcessBuilder("javaw", "-cp", myPath,
 "jp.vmi.selenium.selenese.Main", config.getSuite().getAbsolutePath());

pb.redirectErrorStream(true);

try
{
    Process proc = pb.start();

    InputStream is = proc.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);

    int c;

    while ((c = bis.read()) != -1)
    {
        System.out.write(c);
    }

    int exit = proc.waitFor();

任何指向正确方向的人都会非常感激。

谢谢,

1 个答案:

答案 0 :(得分:1)

好的,如果你绝对必须,你可以尝试这个片段找到你的“当前”JAR:

try
    {
        URL baseUrl = JavaApplication2.class.getProtectionDomain().getCodeSource().getLocation();
        String myPath = (new File(baseUrl.toURI())).getCanonicalPath();
        System.out.println("Path is " + myPath);
    }
    catch (IOException ex)
    {
       // Deal with exception 
    }
    catch (URISyntaxException ex)
    {
       // Deal with exception 
    }

而不是“JavaApplication2”使用您的应用程序/ JAR中的任何类。 (或者只是getClass(),也应该在非静态上下文中工作)