JDK dependency for rJava in MacOS¶
rJava is an interface that allows users/developers to use Java from R. And there are a few R packages depend on it. However getting it to work seems to be a well-known pain. The xlsx is a R package that can both read and write xlsx spreadsheet from R and, unsurprisingly, it depends on rJava. I struggled a lot a couple of years ago and somehow got it work successfully on my old MacBook air. Earlier this year, I got a new MacBook pro, and here the problem comes back.
Installing the xlsx package from CRAN automatically installs the rJava packages, too, because of the dependency. But when I load the package, it throws me an error.
> library(xlsx) Unable to find any JVMs matching version "(null)". No Java runtime present, try --request to install. Error: package or namespace load failed for ‘xlsx’: .onLoad failed in loadNamespace() for 'rJava', details: call: dyn.load(file, DLLpath = DLLpath, ...) error: unable to load shared object '/Library/Frameworks/R.framework/Versions/3.5/Resources/library/rJava/libs/rJava.so': dlopen(/Library/Frameworks/R.framework/Versions/3.5/Resources/library/rJava/libs/rJava.so, 6): Library not loaded: /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home/lib/server/libjvm.dylib Referenced from: /Library/Frameworks/R.framework/Versions/3.5/Resources/library/rJava/libs/rJava.so Reason: image not found In addition: Warning message: In system("/usr/libexec/java_home", intern = TRUE) : running command '/usr/libexec/java_home' had status 1
The error message says that the xlsx package can't be loaded because there is a problem while loading the rJava. And the reason is that the java library was not found. And if I go to terminal to check my java"
$ java -version No Java runtime present, requesting install.
So we need to have the java installed, and according to the error message, it must be 11.0.1. However, the most latest java version on the Oracle website is 12.0.1, and Oracle does not put every historical version on the website. Although 11.0.3 is available, but it's not working! After searching on the internet for a while, I found a github repository that collected all links to the historical version of java, including JDK 11. However, the links are a little out of date since Oracle changed the directory name that stores their archives. The link below downloads the JDK 11.0.1.
And if you want to download the zipped file:
Install it after the downloading finishes, and your rJava dependent packages are good to go. However, if you have a newer version of JDK also installed, and if you load any rJava dependent package in RStudio, the IDE will break, because by default, it is going to use the newest JDK installed. So we need to tell the R session to use jdk-11.0.1, using a single line of code below before loading the package:
> Sys.setenv(JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home')
Enjoy!