在Java程序中执行另一个jar

发布于 2024-08-02 21:26:25 字数 153 浏览 2 评论 0原文

我编写了几个简单的java应用程序,名为A.jar、B.jar。

现在我想编写一个GUI java程序,以便用户可以按下按钮A来执行A.jar,按下按钮B来执行B.jar。

我还想在我的 GUI 程序中输出运行时进程的详细信息。

有什么建议吗?

I had written several simple java applications named as A.jar, B.jar.

Now i want to write a GUI java program so that user can press button A to execute A.jar and button B to execute B.jar.

Also i want to output the run-time process detail in my GUI program.

Any suggestion?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

做个少女永远怀春 2024-08-09 21:26:26

如果你是java 1.6那么还可以执行以下操作:

import javax.tools.JavaCompiler; 
import javax.tools.ToolProvider; 

public class CompilerExample {

    public static void main(String[] args) {
        String fileToCompile = "/Users/rupas/VolatileExample.java";

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        int compilationResult = compiler.run(null, null, null, fileToCompile);

        if (compilationResult == 0) {
            System.out.println("Compilation is successful");
        } else {
            System.out.println("Compilation Failed");
        }
    }
}

If you are java 1.6 then the following can also be done:

import javax.tools.JavaCompiler; 
import javax.tools.ToolProvider; 

public class CompilerExample {

    public static void main(String[] args) {
        String fileToCompile = "/Users/rupas/VolatileExample.java";

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        int compilationResult = compiler.run(null, null, null, fileToCompile);

        if (compilationResult == 0) {
            System.out.println("Compilation is successful");
        } else {
            System.out.println("Compilation Failed");
        }
    }
}
月寒剑心 2024-08-09 21:26:25

如果我理解正确的话,您似乎想在 java GUI 应用程序内部的单独进程中运行这些 jar。

为此,您可以使用:

// Run a java app in a separate system process
Process proc = Runtime.getRuntime().exec("java -jar A.jar");
// Then retreive the process output
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();

缓冲进程的输出始终是一个好习惯。

If I understand correctly it appears you want to run the jars in a separate process from inside your java GUI application.

To do this you can use:

// Run a java app in a separate system process
Process proc = Runtime.getRuntime().exec("java -jar A.jar");
// Then retreive the process output
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();

Its always good practice to buffer the output of the process.

帅冕 2024-08-09 21:26:25

.jar 不可执行。实例化类或调用任何静态方法。

编辑:
创建 JAR 时添加主类条目。

>p.mf(p.mf的内容)

主类:pk.Test

>Test.java

package pk;
public class Test{
  public static void main(String []args){
    System.out.println("Hello from Test");
  }
}

使用 Process 类及其方法,

public class Exec
{
   public static void main(String []args) throws Exception
    {
        Process ps=Runtime.getRuntime().exec(new String[]{"java","-jar","A.jar"});
        ps.waitFor();
        java.io.InputStream is=ps.getInputStream();
        byte b[]=new byte[is.available()];
        is.read(b,0,b.length);
        System.out.println(new String(b));
    }
}

.jar isn't executable. Instantiate classes or make call to any static method.

EDIT:
Add Main-Class entry while creating a JAR.

>p.mf (content of p.mf)

Main-Class: pk.Test

>Test.java

package pk;
public class Test{
  public static void main(String []args){
    System.out.println("Hello from Test");
  }
}

Use Process class and it's methods,

public class Exec
{
   public static void main(String []args) throws Exception
    {
        Process ps=Runtime.getRuntime().exec(new String[]{"java","-jar","A.jar"});
        ps.waitFor();
        java.io.InputStream is=ps.getInputStream();
        byte b[]=new byte[is.available()];
        is.read(b,0,b.length);
        System.out.println(new String(b));
    }
}
偏爱你一生 2024-08-09 21:26:25

希望这有帮助:

public class JarExecutor {

private BufferedReader error;
private BufferedReader op;
private int exitVal;

public void executeJar(String jarFilePath, List<String> args) throws JarExecutorException {
    // Create run arguments for the

    final List<String> actualArgs = new ArrayList<String>();
    actualArgs.add(0, "java");
    actualArgs.add(1, "-jar");
    actualArgs.add(2, jarFilePath);
    actualArgs.addAll(args);
    try {
        final Runtime re = Runtime.getRuntime();
        //final Process command = re.exec(cmdString, args.toArray(new String[0]));
        final Process command = re.exec(actualArgs.toArray(new String[0]));
        this.error = new BufferedReader(new InputStreamReader(command.getErrorStream()));
        this.op = new BufferedReader(new InputStreamReader(command.getInputStream()));
        // Wait for the application to Finish
        command.waitFor();
        this.exitVal = command.exitValue();
        if (this.exitVal != 0) {
            throw new IOException("Failed to execure jar, " + this.getExecutionLog());
        }

    } catch (final IOException | InterruptedException e) {
        throw new JarExecutorException(e);
    }
}

public String getExecutionLog() {
    String error = "";
    String line;
    try {
        while((line = this.error.readLine()) != null) {
            error = error + "\n" + line;
        }
    } catch (final IOException e) {
    }
    String output = "";
    try {
        while((line = this.op.readLine()) != null) {
            output = output + "\n" + line;
        }
    } catch (final IOException e) {
    }
    try {
        this.error.close();
        this.op.close();
    } catch (final IOException e) {
    }
    return "exitVal: " + this.exitVal + ", error: " + error + ", output: " + output;
}
}

Hope this helps:

public class JarExecutor {

private BufferedReader error;
private BufferedReader op;
private int exitVal;

public void executeJar(String jarFilePath, List<String> args) throws JarExecutorException {
    // Create run arguments for the

    final List<String> actualArgs = new ArrayList<String>();
    actualArgs.add(0, "java");
    actualArgs.add(1, "-jar");
    actualArgs.add(2, jarFilePath);
    actualArgs.addAll(args);
    try {
        final Runtime re = Runtime.getRuntime();
        //final Process command = re.exec(cmdString, args.toArray(new String[0]));
        final Process command = re.exec(actualArgs.toArray(new String[0]));
        this.error = new BufferedReader(new InputStreamReader(command.getErrorStream()));
        this.op = new BufferedReader(new InputStreamReader(command.getInputStream()));
        // Wait for the application to Finish
        command.waitFor();
        this.exitVal = command.exitValue();
        if (this.exitVal != 0) {
            throw new IOException("Failed to execure jar, " + this.getExecutionLog());
        }

    } catch (final IOException | InterruptedException e) {
        throw new JarExecutorException(e);
    }
}

public String getExecutionLog() {
    String error = "";
    String line;
    try {
        while((line = this.error.readLine()) != null) {
            error = error + "\n" + line;
        }
    } catch (final IOException e) {
    }
    String output = "";
    try {
        while((line = this.op.readLine()) != null) {
            output = output + "\n" + line;
        }
    } catch (final IOException e) {
    }
    try {
        this.error.close();
        this.op.close();
    } catch (final IOException e) {
    }
    return "exitVal: " + this.exitVal + ", error: " + error + ", output: " + output;
}
}
心在旅行 2024-08-09 21:26:25

以下工作通过使用批处理文件启动 jar 来实现,以防程序作为独立运行:

public static void startExtJarProgram(){
        String extJar = Paths.get("C:\\absolute\\path\\to\\batchfile.bat").toString();
        ProcessBuilder processBuilder = new ProcessBuilder(extJar);
        processBuilder.redirectError(new File(Paths.get("C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt").toString()));
        processBuilder.redirectInput();
        try {
           final Process process = processBuilder.start();
            try {
                final int exitStatus = process.waitFor();
                if(exitStatus==0){
                    System.out.println("External Jar Started Successfully.");
                    System.exit(0); //or whatever suits 
                }else{
                    System.out.println("There was an error starting external Jar. Perhaps path issues. Use exit code "+exitStatus+" for details.");
                    System.out.println("Check also C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt file for additional details.");
                    System.exit(1);//whatever
                }
            } catch (InterruptedException ex) {
                System.out.println("InterruptedException: "+ex.getMessage());
            }
        } catch (IOException ex) {
            System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
        }
        System.out.println("Process Terminated.");
        System.exit(0);
    }

在batchfile.bat 中,我们可以说:

@echo off
start /min C:\path\to\jarprogram.jar

The following works by starting the jar with a batch file, in case the program runs as a stand alone:

public static void startExtJarProgram(){
        String extJar = Paths.get("C:\\absolute\\path\\to\\batchfile.bat").toString();
        ProcessBuilder processBuilder = new ProcessBuilder(extJar);
        processBuilder.redirectError(new File(Paths.get("C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt").toString()));
        processBuilder.redirectInput();
        try {
           final Process process = processBuilder.start();
            try {
                final int exitStatus = process.waitFor();
                if(exitStatus==0){
                    System.out.println("External Jar Started Successfully.");
                    System.exit(0); //or whatever suits 
                }else{
                    System.out.println("There was an error starting external Jar. Perhaps path issues. Use exit code "+exitStatus+" for details.");
                    System.out.println("Check also C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt file for additional details.");
                    System.exit(1);//whatever
                }
            } catch (InterruptedException ex) {
                System.out.println("InterruptedException: "+ex.getMessage());
            }
        } catch (IOException ex) {
            System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
        }
        System.out.println("Process Terminated.");
        System.exit(0);
    }

In the batchfile.bat then we can say:

@echo off
start /min C:\path\to\jarprogram.jar
永不分离 2024-08-09 21:26:25

如果该 jar 在您的类路径中,并且您知道它的 Main 类,则只需调用主类即可。以 DITA-OT 为例:

import org.dita.dost.invoker.CommandLineInvoker;
....
CommandLineInvoker.main('-f', 'html5', '-i', 'samples/sequence.ditamap', '-o', 'test')

请注意,这将使从属 jar 与您的 jar 共享内存空间和类路径,并可能导致潜在的干扰。如果您不想让这些东西被污染,您还有其他选择,如上所述 - 即:

  • 创建一个新的 ClassLoader,其中包含 jar。这样更安全;如果您使用将要使用外来 jar 的知识来构建事物,那么您至少可以将新 jar 的知识隔离到核心类加载器。这就是我们在我的商店中为插件系统所做的事情;主应用程序是一个带有 ClassLoader 工厂的小 shell、API 的副本,并且知道真正的应用程序是应该为其构建 ClassLoader 的第一个插件。插件是一对压缩在一起的 jars——接口和实现。所有类加载器都共享所有接口,而每个类加载器仅了解其自己的实现。该堆栈有点复杂,但它通过了所有测试并且工作得很好。
  • 使用 Runtime.getRuntime.exec(...) (完全隔离 jar,但具有正常的“查找应用程序”、“正确转义字符串”、“特定于平台的 WTF”和运行系统命令的“OMG 系统线程”陷阱。

If the jar's in your classpath, and you know its Main class, you can just invoke the main class. Using DITA-OT as an example:

import org.dita.dost.invoker.CommandLineInvoker;
....
CommandLineInvoker.main('-f', 'html5', '-i', 'samples/sequence.ditamap', '-o', 'test')

Note this will make the subordinate jar share memory space and a classpath with your jar, with all the potential for interference that can cause. If you don't want that stuff polluted, you have other options, as mentioned above - namely:

  • create a new ClassLoader with the jar in it. This is more safe; you can at least isolate the new jar's knowledge to a core classloader if you architect things with the knowledge that you'll be making use of alien jars. It's what we do in my shop for our plugins system; the main application is a tiny shell with a ClassLoader factory, a copy of the API, and knowledge that the real application is the first plugin for which it should build a ClassLoader. Plugins are a pair of jars - interface and implementation - that are zipped up together. The ClassLoaders all share all the interfaces, while each ClassLoader only has knowledge of its own implementation. The stack's a little complex, but it passes all tests and works beautifully.
  • use Runtime.getRuntime.exec(...) (which wholly isolates the jar, but has the normal "find the application", "escape your strings right", "platform-specific WTF", and "OMG System Threads" pitfalls of running system commands.
红颜悴 2024-08-09 21:26:25

首先,我们创建一个 FirstFileOutput 类,它有一个 main 方法,该方法输出一行到稳定输出和一行到稳定错误。对于所有第一个过程,我们将再次创建一个 RuntimeExecCheck 类,它将在启动过程中运行我们的 FirstFileOutput 类,之后 RuntimeExecCheck 类将读取稳定的输出,并从 FirstFileOutput 和输出中读取稳定的错误。

package check;

public class FirstFileOutput{

    public static void main(String[] args) {
        System.out.println("This is output to stable output");
        System.err.println("This is output to stable error");
    }
}



package check;

import java.io.InputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class RuntimeExecCheck {

    public static void main(String[] args) {
        try {
            Runtime runTime = Runtime.getRuntime();
            Process process = runTime.exec("java -classpath C:\\projects\\workspace\\check\\bin check.FirstFileOutput");
            InputStream inputStream = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(inputStream);
            InputStream errorStream = process.getErrorStream();
            InputStreamReader esr = new InputStreamReader(errorStream);

            int n1;
            char[] c1 = new char[1024];
            StringBuffer stableOutput = new StringBuffer();
            while ((n1 = isr.read(c1)) > 0) {
                stableOutput.append(c1, 0, n1);
            }
            System.out.println("Stable Output: " + stableOutput.toString());

            int n2;
            char[] c2 = new char[1024];
            StringBuffer stableError = new StringBuffer();
            while ((n2 = esr.read(c2)) > 0) {
                stableError.append(c2, 0, n2);
            }
            System.out.println("Stable Error: " + stableError.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

First we cerate a class FirstFileOutput having a main method that outputs a line to stable output and a line to stable error. With all first procedure, we'll again create a class RuntimeExecCheck that will run our FirstFileOutput class in starting for process, and after that RuntimeExecCheck class will read the stable output and the stable error from FirstFileOutput and output comes.

package check;

public class FirstFileOutput{

    public static void main(String[] args) {
        System.out.println("This is output to stable output");
        System.err.println("This is output to stable error");
    }
}



package check;

import java.io.InputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class RuntimeExecCheck {

    public static void main(String[] args) {
        try {
            Runtime runTime = Runtime.getRuntime();
            Process process = runTime.exec("java -classpath C:\\projects\\workspace\\check\\bin check.FirstFileOutput");
            InputStream inputStream = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(inputStream);
            InputStream errorStream = process.getErrorStream();
            InputStreamReader esr = new InputStreamReader(errorStream);

            int n1;
            char[] c1 = new char[1024];
            StringBuffer stableOutput = new StringBuffer();
            while ((n1 = isr.read(c1)) > 0) {
                stableOutput.append(c1, 0, n1);
            }
            System.out.println("Stable Output: " + stableOutput.toString());

            int n2;
            char[] c2 = new char[1024];
            StringBuffer stableError = new StringBuffer();
            while ((n2 = esr.read(c2)) > 0) {
                stableError.append(c2, 0, n2);
            }
            System.out.println("Stable Error: " + stableError.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
如何视而不见 2024-08-09 21:26:25

您可以使用以下代码:

    Process process = Runtime.getRuntime().exec(command_string);
    BufferedInputStream successBufferedInputStream = new BufferedInputStream(process.getInputStream());
    BufferedInputStream errorBufferedInputStream = new BufferedInputStream(process.getErrorStream());
    synchronized (process) {
        process.waitFor();
    }

    if (errorBufferedInputStream.available() != ZERO) {
        errorBufferedInputStream.close();
        System.out.println("error stream after jar execution");
    }

    if (process.exitValue() != ZERO) {
       System.out.println("error jar execution");
    }

    if (successBufferedInputStream.available() == ZERO) {
       System.out.println("error");
    }

    StringBuilder response = new StringBuilder();
    while ((successBufferedInputStream.available()) > ZERO) {
        response.append((char) successBufferedInputStream.read());
    }
    successBufferedInputStream.close();

You can use the below code:

    Process process = Runtime.getRuntime().exec(command_string);
    BufferedInputStream successBufferedInputStream = new BufferedInputStream(process.getInputStream());
    BufferedInputStream errorBufferedInputStream = new BufferedInputStream(process.getErrorStream());
    synchronized (process) {
        process.waitFor();
    }

    if (errorBufferedInputStream.available() != ZERO) {
        errorBufferedInputStream.close();
        System.out.println("error stream after jar execution");
    }

    if (process.exitValue() != ZERO) {
       System.out.println("error jar execution");
    }

    if (successBufferedInputStream.available() == ZERO) {
       System.out.println("error");
    }

    StringBuilder response = new StringBuilder();
    while ((successBufferedInputStream.available()) > ZERO) {
        response.append((char) successBufferedInputStream.read());
    }
    successBufferedInputStream.close();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文