繁体   English   中英

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

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

我在下面的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();
    }
}

批处理文件将文件从本地文件夹移动到远程文件夹(当批处理文件没有通过eclipse起作用或通过jenkins调用时,我手动执行了该批处理文件并完成了其工作,这很奇怪。)

谢谢你的帮助

Apache Commons CLI提供了使用Java命令行处理功能。 您也可以使用exit值来了解命令的运行状况。 例如:

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