【问题标题】:java execute script in Tomcatjava在Tomcat中执行脚本
【发布时间】:2018-11-13 13:00:47
【问题描述】:

我创建了一个 spring boot 项目,我在本地 tomcat 上运行(我打算将它部署到网络服务器)。在这个项目中,我创建了一个休息服务,它应该执行一个 .bat 文件。

我的休息服务看起来像这样(它们都不起作用)

@RequestMapping(value = "/esc", method= RequestMethod.GET)
public String esc() throws IOException, InterruptedException {
      String folder = "P:\\Documents\\testcmd";
    String[] cmdarray = new String[]{"cmd -c","dosomething.cmd"};
    ProcessBuilder processBuilder = new ProcessBuilder( cmdarray );
    processBuilder.directory(new File(folder));
    Process process = processBuilder.start();

    int exitCode = -1;
    boolean finished = false;
    while ( !finished ) {
        exitCode = process.waitFor();
        finished = true;
    }
    return folder;
}

@RequestMapping(value = "/ex", method= RequestMethod.GET)
public String executeShellScript(){
    //final String shCmd = "/bin/bash -c helloworld.sh";
    System.out.println("Working Directory = " +
            System.getProperty("user.dir"));
    final String shCmd = "cmd -c P:/Documents/testcmd/dosomething.cmd";
    String output = executeCommand(shCmd);

    return output;
}
private String executeCommand(String command){
    Process p;
    InputStream in = null;
    String value = "";
    try {
        p = Runtime.getRuntime().exec(command);
        in = p.getInputStream();
        int ch;
        while((ch = in.read()) != -1) {
            value = String.valueOf((char)ch);
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    return value;
}

我使用流程构建器和运行时进行了尝试。 我要执行的文件在这个文件夹中:“P:\Documents\testcmd”

甚至可以用tomcat服务器执行本地文件吗?

【问题讨论】:

  • 您是在 Windows 还是 Linux 上运行? (不清楚你调用 /bin/bashcmd -c
  • 我在 windows 上运行这个

标签: java spring rest shell tomcat


【解决方案1】:

我解决了这个问题。 Runtime.getRuntime().exec(command) 的解决方案是正确的。只有我的系统调用是错误的。而不是final String shCmd = "cmd -c P:/Documents/testcmd/dosomething.cmd";,我不得不使用"P:/Documents/testcmd/dosomething.cmd"。另外我不得不更改dosomething.cmd,因为它是错误的。执行纯 java 代码时,该文件将打开一个 cmd 终端,然后在无限循环中打印 hello。我更改了文件内容,而不是终端中的无限循环,它将 hello 打印到另一个文件中。

// method is mapped on root/ex
@RequestMapping(value = "/ex", method= RequestMethod.GET)
public String executeShellScript(){
    System.out.println("Working Directory = " +
            System.getProperty("user.dir"));
    final String shCmd = "P:\\Documents\\testcmd\\dosomething.cmd -c";
    String output = executeCommand(shCmd);

    return output;
}

之前和之后的批处理文件

@echo off
:start
echo hallo
pause
goto start

之后

@echo off
@echo This is a test>> P:/Documents/testcmd/file.txt
@echo 123>> P:/Documents/testcmd/file.txt
@echo 245.67>> P:/Documents/testcmd/file.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-28
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 2020-12-23
    相关资源
    最近更新 更多