简体   繁体   English

在Java / Eclipse中运行批处理(shell / CMD)命令的最佳方法?

[英]Best way to run a batch (shell / CMD) command in Java / Eclipse?

I have created the following code below in Eclipse / java which executes a batch file, which in turn should also execute once all my TestNG tests have executed but sometimes the bat file will execute and sometimes it dosnt do anything at all, any ideas? 我在下面的Eclipse / java中创建了以下代码,该代码执行一个批处理文件,依次执行所有TestNG测试后,该代码也应执行,但有时bat文件将执行,有时它根本不执行任何操作,有什么想法吗?

@AfterSuite(alwaysRun = true) 
public void executeBatFile() {
    try {
        List cmdAndArgs = Arrays.asList("cmd", "/c", "copyPasteImgs.bat");
        File dir = new File(Paths.get(System.getProperty("user.dir") + "/..").toRealPath() + "\\");
        ProcessBuilder pb = new ProcessBuilder(cmdAndArgs);
        pb.directory(dir);
        Process p = pb.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The batch files moves files from a local folder to a remote folder (When the batch file hasnt worked via eclipse or invoked via jenkins I have manually executed the batch file and it did its jobs, very weird...) 批处理文件将文件从本地文件夹移动到远程文件夹(当批处理文件没有通过eclipse起作用或通过jenkins调用时,我手动执行了该批处理文件并完成了其工作,这很奇怪。)

thanks for your help 谢谢你的帮助

Apache Commons CLI provides functionalities to handle using command line from java. Apache Commons CLI提供了使用Java命令行处理功能。 You can also use the exit value to have an idea about what is going on with your command. 您也可以使用exit值来了解命令的运行状况。 For example: 例如:

String command = "dir";
CommandLine oCmdLine = CommandLine.parse(command);
        DefaultExecutor oDefaultExecutor = new DefaultExecutor();
        oDefaultExecutor.setExitValue(0);
        try {
            int iExitValue = oDefaultExecutor.execute(oCmdLine);
        } catch (ExecuteException e) {
            System.err.println("Execution failed.");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("permission denied.");
            e.printStackTrace();
        } 

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

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