Execute commands or cmd scripts by java do not work [duplicate]

4

I'm having trouble executing some commands through java. If I run them directly from Netbeans or run the project directly from my machine it works perfectly any of the commands below:

String comando = "cmd /c \"//Server/Sistema/Scripts/executa.bat\"";
exec = Runtime.getRuntime().exec(comando);

or

String comando = "cmd /c \"tskill servico\"";
exec = Runtime.getRuntime().exec(comando);

But as you can see .bat as well as the system, it will be on a server in the network and only the shortcut is made available to the user. So when testing on a user machine or the command does not work, or I have to run it several times for it to work, remembering that if I go in the script folder and run it manually it will work.

The strange thing is that on the same button that I call the method of this operation, I also call another method where I open a page in chrome with the command:

String comando = "cmd /c start chrome.exe http://link";

and this works perfectly, no matter how many times I click.

I do not know if this could be a network problem, or the script / command when run by java, runs on the server and not on the user machine where there is only the shortcut. All users have permissions to the system folder.

I also tried using the command as follows:

String[] comando = {"\"//Server/Sistema/Scripts/executa.bat\""};
ProcessBuilder builder = new ProcessBuilder("cmd", "/c",
String.join("& ", comando));
Process p = builder.start();

But the same thing happens, right from Netbeans it runs, but by the jar, I have to run several times.

If anyone has any suggestions, thank you.

    
asked by anonymous 12.06.2017 / 14:31

1 answer

0

I solved the problem. The workaround was to change the script to:

tasklist | find /i "servico.exe"
IF %ERRORLEVEL% == 0 (
    taskkill /f /im "servico.exe"
    taskkill /f /im "servico2.exe"
    ping -n 2 localhost>nul
)

In this way the script will search if the service is running, if it is it will finish the 2 services that I want. At first it worked, I do not know why otherwise it did not end services through the system, just straight from Netbeans or running the script in hand. But anyway, thanks for the help!

    
12.06.2017 / 18:23