便携Java程序如何从主程序旁子目录启动JVM?以Eclipse为例
Awesome question! I’ve set up portable Eclipse on USB drives for on-the-go coding and troubleshooting before, so let me break down exactly how this works on Windows.
The Core Idea: Eclipse’s Flexible Java Detection
Eclipse was built to be flexible about where it pulls its Java runtime—unlike some tools that hardcode paths to system-wide Java installs. It prioritizes local, embedded Java environments over global ones, which is what makes the portable setup possible.
1. Embedding a JRE/JDK in Your Eclipse Folder
First, you (or a pre-configured Eclipse package) place a full JRE or JDK in a folder right next to Eclipse’s main binary files (like eclipse.exe). Common folder names are jre or jdk, but it can be anything as long as you point Eclipse to it.
Eclipse’s launcher checks this local directory first before looking for system-wide Java. That’s why even if the host PC has no Java installed, Eclipse can still find its own embedded version.
2. The eclipse.ini File: Your Portability Control Panel
The real magic lives in the eclipse.ini file, located in the same folder as eclipse.exe. You can explicitly tell Eclipse exactly where to find its Java runtime using relative paths—so it works no matter what drive letter your USB stick gets assigned.
For example, if your JRE is in a jre folder at the same level as eclipse.exe, add these lines to eclipse.ini (make sure they come before the -vmargs line):
-vm .\jre\bin\javaw.exe
The . here refers to the current directory (where eclipse.exe is located), so this relative path will always resolve correctly, even if your USB moves from D: to F: to any other drive.
3. Windows-Specific Path Resolution
Windows handles relative paths based on the executable’s location, not the current working directory. So when eclipse.exe reads that .\jre\bin\javaw.exe path, it always looks in the folder right next to itself—perfect for portable setups.
Eclipse also doesn’t rely on Windows registry entries for Java (like the ones created when you install system-wide Java) or the PATH environment variable when you specify a local JRE via eclipse.ini.
4. Self-Contained Runtime Components
Your embedded JRE/JDK includes everything Eclipse needs:
javaw.exe: The Java runtime executable that launches Eclipse itselfjavac.exe(if using a JDK): The compiler for building your Java code- Core class libraries (like
rt.jar) with all standard Java APIs - All supporting DLLs and configuration files required to run Java on Windows
Since all these components live on the USB drive, Eclipse doesn’t need anything from the host PC’s system files.
Bonus: Portable Workspace
You can take this a step further by setting Eclipse to use a workspace on the USB drive instead of the local PC. Just go to File > Switch Workspace > Other and select a folder on your USB. That way, all your projects, settings, and plugins stay with the drive too.
内容的提问来源于stack exchange,提问作者Tabernero

