I want to verify something, because in my head it makes sense, but in Java, it doesn't work.
I am trying to run another Jar file through my application. A Minecraft server, to be precise. I have all the basics down (using ProcessBuilder
, executing with arguments, waiting for an exit code, etc.), but there is one thing that I cannot figure out. Sending commands to the application. Here part of my CommandLineSender
class:
public class CommandLineSender extends Thread {
private BufferedWriter output;
private InputStream source; // Set to System.in when creating the object
private boolean stopRequested;
public CommandLineSender(Process sendTo, InputStream source) {
this.output = new BufferedWriter(new OutputStreamWriter(sendTo.getOutputStream()));
this.source = source;
System.out.println("Source InputStream initiated: " + source.toString());
this.stopRequested = false;
}
@Override
public void run() {
System.out.println("Run called.");
Scanner cmdScanner = new Scanner(source);
while (cmdScanner.hasNextLine() && !stopRequested) {
System.out.println("Has next line");
String msg = cmdScanner.nextLine();
write(msg);
System.out.println("Wrote: " + msg);
}
// Close the scanner and BufferedWriter
System.out.println("Closed.");
}
// Other various methods
protected void write(String msg) {
try {
output.write(msg);
} catch (IOException e) {
System.err.println("Unable to write message because of an unhandled IOException: " + e.getMessage());
}
}
The output I get is this:
(Default Minecraft server output)
help // My command
Has next line
Wrote: help
This may not matter, but I am executing my server with these arguments:
java -Xmx1024M -Xms1024M -jar (path to server jar) nogui
Thank you for your time.
Here is an example of a Java program that manipulates a C program through its process (you can manipulate a Java program too). I wrote this some years ago. There is the receiver program in C or Java and the sender in Java. Take a look:
C Receiver
Java Receiver (equal the C program)
Java Sender
To run the code, compile the C program or the MessageReceiver class. Put the executables in the same folder of your Sender class, compiles it and run. The "end" command will finish the receiver and the sender.
Take a look in this article too: http://www.javaworld.com/jw-12-2000/jw-1229-traps.html