0

I need to exec a jar file and redirect the output from my executed process to the output of my main process.

I using the following code :

val command = "java.exe -version"
val p = Runtime.getRuntime().exec(command)
val buf = p.getInputStream()
val inputAsString = buf.bufferedReader().use { it.readText() }
println(inputAsString)

I have no output...

I have tested this code :

val command = "cmd /c chcp"
val p = Runtime.getRuntime().exec(command)
val sc = Scanner(p.inputStream)
println(sc.nextLine())
sc.close()

I have an output but when I replace "cmd /c chcp" I have an error...

How can I read the output of "test.jar" which write "ok" for example ?

3
  • 2
    Most programs are sending their diagnostics output to STDERR instead of STDOUT (like java -version). Have you tried reading from there: val buf = p.errorStream? Commented Dec 17, 2017 at 19:37
  • For java -version reading the errorStream work. But when I use "java -jar myfile.jar someargs" It didn't work... Commented Dec 17, 2017 at 19:46
  • Do you know if myfile.jar prints to stderr or stdout? You should consider using ProcessBuilder instead of Runtime.exec, because then you can choose to redirect stderr to stdout so you only have to read from the 1 stream. Commented Dec 20, 2017 at 13:11

1 Answer 1

1
    val p = Runtime.getRuntime().exec(command)
    p.waitFor()
    val stdOut = IOUtils.toString(p.inputStream, Charsets.UTF_8)
    val stdErr = IOUtils.toString(p.errorStream, Charsets.UTF_8)

using org.apache.commons.io for IOUtils

Sign up to request clarification or add additional context in comments.

1 Comment

I spent sometime with some errors while I was trying to get outputStream and errorStream from stdout and stderr, but as tom says, it's inputStream, not outputStream.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.