running mvn using ProcessBuilder

好久不见. 提交于 2019-12-02 02:06:16

问题


I had created a class which create process using ProcessBuilder and then launch process

ProcessBuilder pb = new ProcessBuilder("mvn","exec:java","-Dexec.mainClass="+"FunnyClass");

Now when I m running this class on linux box, it run fine, but on windows it give me error, stating something like 'mvn' not found, I need to change to

ProcessBuilder pb = new ProcessBuilder
                       ("mvn.bat","exec:java","-Dexec.mainClass="+"FunnyClass");

But if I am running command on command prompt "mvn exec:java -Dexec.mainClass=FunnyClass", it run fine. So why I need to give mvn.bat in processbuilder.

Is there any solution to it?

my java application is going to run on both windows & linux boxes, So what should I do?


回答1:


This happens because the windows shell (cmd) has a feature: it tries to add extensions exe, 'bat', 'cmd' to command line you are running. Once it finds the first match (i.e. file that really exists in file system) it runs it.

In case of maven you have unix shell script mvn that cannot be executed on windows and windows batch file '.bat'. Command prompt adds '.bat' to 'mvn' that you type in command prompt, sees that the file exists and runs it.

When you are running process from java you do not have shell, so no-one does this job. I'd suggest you to check the operating system and hold command per OS. If you want clear solution create resource file cmd.properties:

mvn.windows = mvn.bat
mvn.unix = mvn

Now check OS using system property os.name and create command using data from cmd.properties.

Alternative solutionis to run command using cmd /c on windows and '/bin/sh -c' on unix but it does not simplify anything, so I'd avoid this.



来源:https://stackoverflow.com/questions/7966194/running-mvn-using-processbuilder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!