exit the batch file after running using java - java

I know how to start the batch file using java code.
When i run the batch file command prompt is opened.
To close the command prompt i am using the taskill /im cmd.exe.
but the problem is that the command prompt that is used to start the jboss is also closed.
i want to kill the cmd with a particular process id.
How do i get the process id of a particular cmd promt and kill that using java

Run the batch file with cmd.exe /c job.bat. The /c switch carries out the command and then terminates the command interpreter.

can't you add exit to your batch file to exit it's own command prompt. Uisng taskill seems overkill for just closing one command prompt, don't you think?
PS: I've never worked on batch files just the command prompt so I'm assuming it accepts the same commands.

Here is the solution that works: to close command window after executing the commands from the batch (.bat) file you need to add "exit" (without the quotes) in a new line of your batch file. If you want to delay the execution this is the way and it works:
public class TestSleep
{
public static void main ( String [ ] args )
{
System.out.println("Do this stuff");
try
{
Thread.currentThread().sleep(3000);
}
catch ( Exception e ) { }
System.out.println("Now do everything after this");
}
}
Cheers

If you start the batch file with Runtime.exec(), it returns you a Process object. Calling the destroy() method will kill that process.

Although this seems to be an old question and probably resolved.. I struggled with the same thing for a long time.. Finally this works
String command = "cmd.exe /c build.bat";
Runtime rt = Runtime().getRuntime();
Process pr = rt.exec(command);

I too had the same problem. I first used as
Runtime.getRuntime().exec("cmd.exe start /c test.bat");
Then I tried as below. It works fine.
Runtime.getRuntime().exec("cmd.exe /c start test.bat");
Try this.

Related

How can i execute multiple commands with JAVA code?

I need to restart my Tomcat server from Java code. I'm a beginner in Java. I try to do that by cmd. I need to stop tomcat then restart it. I try this code. It works with just two commands (one &&) and it doesn't work if I add a third command (two && in the line exec("cmd /c start cmd.exe ...)).
PS: If another way exists to restart Tomcat with Java code please tell me
public class restart_tomcat {
public static void main(String[] args) throws SDKException, IOException {
Runtime rt = Runtime.getRuntime();
try {
// Process process1 = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + cmd1);
rt.exec("cmd /c start cmd.exe /K \"cd C:\\\\Program Files (x86)\\\\SAP BusinessObjects\\\\tomcat\\\\bin&&startup.bat\"");
System.out.println("succesful");
} catch (IOException e) {
e.printStackTrace();
}
}
}
It would be good to know why do you need to start/stop Tomcat from java code, is that a homework or something else? In the real-world, we have initialization scripts that can start/stop it by simply running them from the terminal. You can automate that with a very simple shell script (yourscript.sh) and add the following content:
#!/bin/bash
<path_to_tomcat>/bin/shutdown.sh
<path_to_tomcat>/bin/startup.sh
If you really need to do it from Java code, you may find your answer in one of these resources:
Start and Stop Tomcat from java code
Restart Tomcat with Java
Start and Stop Tomcat from java code
How to start Tomcat Server programmatically in Java
how to restart tomcat from a running webapp?

Runtime.getRuntime().exec() doesn't execute some commands

I'm beginner at java and have some problems. I've read several topics about this theme but none of them worked for me. Here is my code:
try
{
Console console = System.console();
String command;
while(true)
{
command = console.readLine("Enter input:");
Process proc = Runtime.getRuntime().exec(command);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
}
}
catch(Exception e) {}
So what I'm trying is to make a java program and run terminal commands in it(I'm using linux). This program works with commands like "ls" "ps ef" and others but it doesn't work when I type "cd". I know that cd makes different process and should be used this way: "Runtime.exec(String command, String[] envp, File dir)". My questions is:
How to make my program run all kinds of terminal commands? Sorry if question sound silly. Thank you.
The cd command is a shell built-in command. There is no shell when you run a command via exec(...). Indeed, if you try to find a cd command in any of your system's bin directories, you won't find one ... because it is impossible to implement as a regular command.
If you are trying to use cd to change the current directory for the JVM itself, that won't work because a command can only change the current directory of itself and (after that) commands that it launches itself. It can't change its parent processes current directory.
If you are trying to use cd to change the current directory for subsequent commands, that won't work either. The context in which you set the current directory ends when the command finishes.
In fact, the right way to change the directory for a command run using exec is to set it via the ProcessBuilder API itself.
How to make my program run all kinds of terminal commands?
You can't. Some of the "terminal commands" only make sense as shell commands, and that means you need a shell.
I suppose, you could consider emulating the required behaviour in your Java code. That would work for cd ... but other commands are likely to be more difficult to cope with.
(For what it is worth, it is possible to implement a POSIX compatible shell in Java. It is just a LOT of work.)
you've actually got to run the console you want to use (ie sh, csh, bash, etc) and then use the process OutputStream to feed in commands
I think the Problem is not your Code, the command is the problem...
what do you want to see if your command is cd ??
In Background it changes the path but you get nothing back.
Changing the Directory is not processing any output.
This worked for me:
Runtime.getRuntime().exec(new String[]{ "/system/bin/sh", "-c", "ls -l" } );

Enter commands in the command prompt after it's been opened in Java?

I would like to know how to enter commands into the cmd.exe (command prompt window) , after its been opened?
I have the code below to open cmd.exe:
Runtime rt= Runtime.getRuntime();
Process process= rt.exec("cmd.exe /c start cd c:\\ExecutionSDKTest_10.2.2");
But after it's been opened, I'd like to enter "ant compile" or any line, how do I do that??
The normal way to do this would be to put the commands in a script and execute the script.
You will need to consume the output of the child process (stdout and stderr) on separate threads, or your process will block.
you dont need to open the command line to compile a program with a running program, check this out how to compile & run java program in another java program?
Not exactly the answer to you question. But you can use ProcessBuilder to set your process current directory (so you don't need to call "cd ..." anymore)
Try to pass a List to the ProcessBuilder
final List<String> l = new ArrayList<String>();
final String cmd = "C:/Program Files/Java/jre6/bin/";
l.add("C:\\WINNT\\system32\\cmd.exe ");
l.add("cd " + cmd);
l.add("dir");
l.add("java.exe -version");

Using Java to run Command Line commands in order

I'm writing a program that needs to be able to open and terminate a Minecraft server via command prompt. The code I have for it so far is this:
Runtime.getRuntime().exec("cd ./Server"); //go to the server directory
Process server = Runtime.getRuntime().exec("java -Xmx1024M -Xms1024M -jar minecraft_server.exe nogui"); //run minecraft server in nogui mode
Thread.sleep((long)(1000*60*.5)); //wait 30 seconds
Runtime.getRuntime().exec("stop"); //terminate the server
Thread.sleep((long)(1000*60*.5)); //wait 30 seconds
server.destroy(); //forcibly terminate the server assuming it hasn't already
System.exit(0);
This is just the basic logic code I have come up for it. I have tried using BufferedWriters but they just don't work and it gets an error even by doing the cd command. I am useing Minecraft_Server.exe which is at minecraft.net/download.jsp. The "stop" command runs while the process is active and tells the program to save the server and then terminate. Do I need to be using Threads in some way. Please help :) I've put several hours trying to find the answer already and I'm just clueless lol.
Your "cd ./Server" command, I think is going to lose context here, because the next call to exec isn't going to get the results of the first call. In other words, each call to exec is completely independent of other calls to exec.
Try putting some of this in a shell script instead, and simply exec the script. If you're controlling the server via the command line anyway, then this isn't any more complex than what you've already tried.
You might want to the look at the ProcessBuilder (here) where you can specify the working directory that will be used for all the command you want to execute after.
Each command is run as a separate process.
Your "cd ./Server" has no effect on the commands you run after.
Do you have a command line program called stop?
I would write
Thread.sleep(30 * 1000); // 30 Seconds.
and I wouldn't call System.exit(0);
To run command in particular dir use special version of exec
public Process exec(String command, String[] envp, File dir)
where dir is working dir for the process
Try putting the commands in a string array :
String[] cmd = { "cd","./Server" };
and
String[] cmd2 = {"java", "-Xmx1024M", "-Xms1024M", "-jar", "minecraft_server.exe", "nogui"}
Then try to
Runtime.getRuntime().exec(cmd); //go to the server directory
Process server = Runtime.getRuntime().exec(cmd2); //run minecraft server in nogui mode
Thread.sleep((long)(1000*60*.5)); //wait 30 seconds
Runtime.getRuntime().exec("stop"); //terminate the server
Thread.sleep((long)(1000*60*.5)); //wait 30 seconds
server.destroy(); //forcibly terminate the server assuming it hasn't already
System.exit(0);
Also stop will do nothing since you do not reference what to stop.

close a particular command prompt

I have opened a commnad prompt using java program
and another command prompt manually. Now my requirement is that i need to close the command prompt that i have opened by java program using the program.
I tried to close this by giving rt.exec("taskkill /IM cmd.exe");
But the problem is that the command prompt that i have opened manually is aslo closed which i dont want.
Help needed.
Thanks in advance
if you're using Runtime.getRuntime().exec(), it returns a Process object. You should hold on to that and call Process.destroy() when you're done.
It's simple -
Step 1 - Create a batch file (say closeCMD.bat)
Step 2 - write exit in closeCMD.bat
Step 3 - call above batch file in your java code as below -
Runtime.getRuntime().exec("cmd /c start closeCMD.bat");
That's it !! Cheers!!
you can try to program "exit" into the command prompt after you are done with your tasks in command prompt

Categories

Resources