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 run开发者_如何学JAVAs 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.
精彩评论