在macOS High Sierra(Java 9环境)下安装rJava遇问题求助
Hey there, let’s work through this rJava installation headache together—conflicting Java versions (Apple Java 6 + Oracle Java 9) are almost certainly the culprit here. Here’s a step-by-step fix that’s worked for me and other community members:
1. Lock in Oracle Java 9 as Your Active Environment
First, we need to make sure the system prioritizes Java 9 over Apple Java 6:
- Locate your Oracle Java 9 install path (it’s typically this, but double-check if yours differs):
/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home - Set your
JAVA_HOMEto point directly to this path:export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home - Verify you’re using Java 9 with these commands (both should output Java 9 version info):
java -version javac -version
2. Reconfigure R to Use Java 9
Your earlier sudo R CMD javareconf probably picked up Apple Java 6 instead of Java 9. Let’s force it to use the correct version:
sudo R CMD javareconf JAVA_HOME=$JAVA_HOME
This ensures R links to Java 9’s headers and libraries instead of the older Apple Java 6.
3. Clean Up Partial rJava Installs (If Any)
If you’ve tried installing rJava before, remove any leftover files to avoid conflicts:
- Open R (don’t use
sudo) and run:if ("rJava" %in% installed.packages()) remove.packages("rJava") - Quit R once this finishes.
4. Install rJava from Source with Correct Flags
Before installing, set up preprocessor flags to point to Java 9’s macOS-specific headers:
export JAVA_CPPFLAGS="-I${JAVA_HOME}/include -I${JAVA_HOME}/include/darwin"
Now install rJava without unsetting JAVA_HOME (we’ve already configured it correctly):
R --quiet -e 'install.packages("rJava", type="source", repos="http://cran.us.r-project.org")'
Note: Never use sudo to install R packages—it can cause permission issues down the line.
5. Verify the Installation
Open R and test if rJava loads properly:
library(rJava) .jinit()
If no errors appear, you’re all set!
Quick Troubleshooting
- If you see a "JNI_CreateJavaVM failed" error: Restart your terminal to reset lingering environment variables, then double-check
JAVA_HOMEand re-runjavareconf. - If header files are missing: Confirm the
JAVA_CPPFLAGSpath matches your Java 9 install—macOS stores JNI headers in theinclude/darwinsubfolder.
内容的提问来源于stack exchange,提问作者Christopher Costello

