1.使用 Homebrew 安装
Homebrew 是 macOS 上的包管理工具,可以方便地安装各种软件。以下是使用 Homebrew 安装 Java 的步骤:
1.1安装 Homebrew(如果尚未安装):
打开终端并运行以下命令:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"1.2使用Homebrew安装java
MacBook-Pro Downloads % brew reinstall openjdk
MacBook-Pro Downloads % brew reinstall openjdk
==> Fetching openjdk
==> Downloading https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles/openjdk-22
Already downloaded: /Users/test/Library/Caches/Homebrew/downloads/379700ea42147ba7945c9552d8319cbb74a90f1cf3766e6b4ab6da2510f79956--openjdk-22.0.1.arm64_sonoma.bottle.tar.gz
==> Reinstalling openjdk
==> Pouring openjdk-22.0.1.arm64_sonoma.bottle.tar.gz
==> Caveats
For the system Java wrappers to find this JDK, symlink it with
sudo ln -sfn /opt/homebrew/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk
openjdk is keg-only, which means it was not symlinked into /opt/homebrew,
because macOS provides similar software and installing this software in
parallel can cause all kinds of trouble.
If you need to have openjdk first in your PATH, run:
echo 'export PATH="/opt/homebrew/opt/openjdk/bin:$PATH"' >> ~/.zshrc
For compilers to find openjdk you may need to set:
export CPPFLAGS="-I/opt/homebrew/opt/openjdk/include"
==> Summary
🍺 /opt/homebrew/Cellar/openjdk/22.0.1: 601 files, 328.5MB
==> Running `brew cleanup openjdk`...
Disable this behaviour by setting HOMEBREW_NO_INSTALL_CLEANUP.
Hide these hints with HOMEBREW_NO_ENV_HINTS (see `man brew`).
MacBook-Pro Downloads %2.创建符号链接:
执行以下命令创建符号链接,使系统能够找到安装的 OpenJDK:
sudo ln -sfn /opt/homebrew/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk3.设置环境变量:
根据您使用的 shell(如 zsh 或 bash),编辑相应的配置文件(~/.zshrc 或 ~/.bash_profile),添加以下环境变量设置:
echo 'export PATH="/opt/homebrew/opt/openjdk/bin:$PATH"' >> ~/.zshrcecho 'export PATH="/opt/homebrew/opt/openjdk/bin:$PATH"' >> ~/.bash_profile4.重新加载配置文件:
保存配置文件并关闭编辑器,然后运行以下命令使新的配置生效:
source ~/.zshrc # 如果使用 zsh shell
source ~/.bash_profile # 如果使用 bash shell5.验证安装:
最后,再次运行以下命令来验证 Java 是否正确安装和配置:
MacBook-Pro Downloads % java --version
openjdk 22.0.1 2024-04-16
OpenJDK Runtime Environment Homebrew (build 22.0.1)
OpenJDK 64-Bit Server VM Homebrew (build 22.0.1, mixed mode, sharing)-.-
评论区