Reputation: 85
I need to start jar and provide input to it. I've found how to start jar, which works without problems, using Runtime#getRuntime#exec, and I've also found that
String command = "stop";
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
bufferedWriter.write(String.format("%s\n", command));
bufferedWriter.flush();
should do the job. But the problem is, it just doesn't work for me, it literally does nothing. Does anyone know how to do that? Process:
public static Process startJar(File jarFile, String flags, String args, @Nullable File dir) throws IOException {
if (dir == null){
return Runtime.getRuntime().exec(String.format("cmd /c start /wait \"\" java -jar %s \"%s\" %s",flags ,jarFile.getAbsolutePath(), args));
}
return Runtime.getRuntime().exec(String.format("cmd /c start /wait \"\" java -jar %s \"%s\" %s", flags, jarFile.getAbsolutePath(), args), null, dir);
}
Upvotes: 4
Views: 288
Reputation: 85
The problem was, that I was starting that jar in a new window (cmd /c start), after removing that, everything works without a problem.
Upvotes: 0
Reputation: 499
If the input is commandline args, pass it to exec
directly.
If not, and assuming process
is the other jar you are running, you'll need to write to the InputStream of process
, not the OutputStream. process.getOutputStream()
will give you the stream to which the process
is outputting its results, not where it's reading its input from.
EDIT: After Taschi pointed out that the code is correct
I found another question similar to yours. The accepted answer states that you have to either close the writer
or pass a \n
in order for it to work. Try that. If it still doesn't work, make sure the other JAR you're running is actually waiting for input on its STDIN.
Upvotes: 2
Reputation:
I assume your process is blocked because it tried to write something to its output, and you did not read it. The API doc states:
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.
So, read from process.getInputStream() and process.getErrorStream() unless both of them are empty, and then it should process your input just fine.
See here: Starting a process in Java? for a possible example on how to read.
Upvotes: 1