简体   繁体   English

如何使用 JAVA 代码执行多个命令?

[英]How can i execute multiple commands with JAVA code?

I need to restart my Tomcat server from Java code.我需要从 Java 代码重新启动我的 Tomcat 服务器。 I'm a beginner in Java.我是 Java 的初学者。 I try to do that by cmd.我尝试通过 cmd 来做到这一点。 I need to stop tomcat then restart it.我需要停止 tomcat 然后重新启动它。 I try this code.我试试这段代码。 It works with just two commands (one &&) and it doesn't work if I add a third command (two && in the line exec("cmd /c start cmd.exe...) ).它只适用于两个命令(一个 &&),如果我添加第三个命令(在exec("cmd /c start cmd.exe...)行中的两个 && ),它将不起作用。

PS: If another way exists to restart Tomcat with Java code please tell me PS:如果有另一种方法可以用 Java 代码重启 Tomcat 请告诉我

public class restart_tomcat {

    public static void main(String[] args) throws SDKException, IOException {
        Runtime rt =  Runtime.getRuntime();

        try {
            // Process process1 = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + cmd1);
            rt.exec("cmd /c start cmd.exe /K \"cd C:\\\\Program Files (x86)\\\\SAP BusinessObjects\\\\tomcat\\\\bin&&startup.bat\"");
            System.out.println("succesful");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

It would be good to know why do you need to start/stop Tomcat from java code, is that a homework or something else?很高兴知道为什么需要从 java 代码启动/停止 Tomcat,这是作业还是其他? In the real-world, we have initialization scripts that can start/stop it by simply running them from the terminal.在现实世界中,我们有初始化脚本,可以通过简单地从终端运行它们来启动/停止它。 You can automate that with a very simple shell script (yourscript.sh) and add the following content:您可以使用非常简单的 shell 脚本 (yourscript.sh) 自动执行此操作并添加以下内容:

#!/bin/bash
<path_to_tomcat>/bin/shutdown.sh
<path_to_tomcat>/bin/startup.sh

If you really need to do it from Java code, you may find your answer in one of these resources:如果您确实需要从 Java 代码中执行此操作,您可以在以下资源之一中找到答案:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM