When making a call using rJava, is there a way to capture the output java writes to the console/stdout in a character vector in R? Is there a way to do this without redirecting java's stdout to file and having R read the file?
In my specific use case, I'm connecting to a database using RJDBC and the server will send back useful information that gets printed to the console. I'd like to parse these messages, extract some information, and take action accordingly.
When I make a function call that runs java code, any console output is relayed to the RStudio console, but capture.output
doesn't seem to work (I've tried type = "output"
as well)
rJava::.jinit()
jText <- capture.output(
rJava::J("java/lang/System")$out$println("Write this down"),
type = "message"
)
identical(jText, character(0))
#> [1] TRUE
I can do this by redirecting java stdout to file, but is there a way that avoids writing to file? For example, I can extract to whom HAL 9000 is talking this way:
rJava::.jinit()
jSys <- rJava::J("java/lang/System")
jOut <- tempfile(fileext = ".txt")
jOrigOut <- jSys$out
jPS <- rJava::.jnew("java/io/PrintStream", jOut)
jSys$setOut(jPS)
jSys$out$println("I'm sorry Dave. I'm afraid I can't do that")
jSys$setOut(jOrigOut)
msg <- readLines(jOut)
regmatches(msg, regexpr("(?<=I'm sorry ).*(?=\\.)", msg, perl = TRUE))
#> [1] "Dave"
Created on 2019-07-19 by the reprex package (v0.3.0)
but is there a way that avoids using the temp file?