2

I have block like this one:

task print() {
    doLast {
        println("stop-1")
        println(getJavaVersion())
        println("stop-3")
    }
}

def getJavaVersion() {
    def out = new ByteArrayOutputStream()
    exec {
        workingDir 'C:/Program Files/Java/jdk1.7.0_80/bin'
        commandLine 'cmd', '/c', 'java', '-version'
        standardOutput = out
    }

    println 'stop-2'
    return out.toString()
}

And I would expect that the output will be printed inside doLast block of print task, but it's printed just after exec block.

This is the output:

Executing tasks: [print]

Parallel execution with configuration on demand is an incubating feature.

> Task :gcUnicorn-core:print
stop-1
java version "1.7.0_80"
Java(TM) SE Runtime Environment (build 1.7.0_80-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.80-b11, mixed mode)
stop-2

stop-3

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed

As you can see, the output stream is empty.

I went trough Gradle's documentation and many examples I found, but have no luck to solve it.

Gradle: 4.10.2, Windows: 7, jdk1.8.0_192

Thank you for any advice.

Naman
  • 27,789
  • 26
  • 218
  • 353
franta kocourek
  • 1,289
  • 13
  • 19

1 Answers1

3

Actually java -version prints the message to the standard error and not standard output (stdout), so instead try:

errorOutput = out
Mahozad
  • 18,032
  • 13
  • 118
  • 133
Ryotsu
  • 786
  • 6
  • 16
  • Hi. Ouch, It never occured to me that the output could be written into `errorOutput`. Do you know why the output is not written into `standardOutput`? Can you point me to some documentation regarding `out` reference? – franta kocourek Nov 23 '18 at 09:26
  • @frantakocourek its the command that writes to the error stream not gradle. Try `java -version 1>std.txt 2>err.txt` and have a look at the files. – Ryotsu Nov 23 '18 at 09:28
  • I will accept your answer. Thank you for it! Can you please point me to some documentation about it? I would like to know why it writes into error stream. Thank you. – franta kocourek Nov 23 '18 at 09:30
  • 1
    @frantakocourek actually i'd expect java's man page to document where it prints the version of java but it dosen't but i did find this https://stackoverflow.com/questions/23464917/why-does-java-version-print-its-output-to-error-stream – Ryotsu Nov 23 '18 at 09:36
  • Ok, saved my day anyway :) Thanks. – franta kocourek Nov 23 '18 at 09:38
  • Thanks! You really saved me! I couldnt find the answer why standardOutput was always empty when I used java --version – starryn1ght Jun 13 '23 at 13:39