Run bat file from java code to get desired result

2019-08-31 02:46发布

问题:

I have the following problem. I got a bat file that runs testcomplete test. After the test is finished in testcomplete, the app closes and exit code is passed back to the bat. Still in bat file i create a txt file called result and then depending on exit code i write to it successs, failure etc. When i run that bat file in Windows 7 i can see that test is being executed and after it's finished result.txt file appears with information i need. But when i simply run this same bat file from java code:

Process p1 = Runtime.getRuntime().exec(batch);

after the test is finished, file does not appear. Is there any way to get this to work fine? What should i change?

Script code is more less like that:

@ECHO OFF
"...\Bin\TestComplete.exe" "sometext.pjs" /r 
/p:sometext PathToApp="sometext.jnlp" Login=ads Password=ass  /t:"sometext|sometext" /exit 
IF ERRORLEVEL 3 GOTO CannotRun
IF ERRORLEVEL 2 GOTO Errors
IF ERRORLEVEL 1 GOTO Warnings
IF ERRORLEVEL 0 GOTO Success

:CannotRun
ECHO The script cannot be run >> "result.txt"
GOTO End

:Errors
ECHO There are errors >> "result.txt"
GOTO End

:Warnings
ECHO There are warnings >> "result.txt"
GOTO End

:Success
ECHO No errors >> "result.txt"
GOTO End

:End

回答1:

I would guess that you need to specify your Working Directory, by using an overloaded version of exec:

exec(String command, String[] envp, File dir)



回答2:

Another thing is, that you should always read the InputStream of the process. If you don't the process might hang.