如何在Windows批处理文件中通过指定路径JRE运行Jar包并关闭黑窗口
Hey there! Let's sort out how to get that black command prompt window to close automatically once your JAR finishes running. Depending on whether your JAR is a GUI application (no console output) or a console-based tool, here are a few reliable solutions:
Method 1: Use start for GUI Apps (Cleanest Approach)
If your JAR is a GUI app (like a Swing/JavaFX app with no console logs you need to see), wrap your Java command with the start command. This launches the JAR in a separate process, letting the batch file exit right away:
@echo off start /b "%JAVA_HOME%\bin\java.exe" -jar -Xmx128m -Xms64m -XX:MaxPermSize=64m "%~dp0Myfolder\dist\Myjar.jar" %* exit
@echo offhides raw command text from being printed in the window (makes it look cleaner).start /bruns the Java process without spawning an extra window, and doesn't wait for it to finish—so the batch file can close immediately.exitensures the window closes right after launching the JAR, no hanging around.
Method 2: Wait for the JAR to Finish, Then Close (Great for Console Apps)
If your JAR is a console-based tool that outputs logs or needs to run to completion before closing, just add exit at the end of your existing command. This way, the window stays open while the JAR runs, then closes as soon as it's done:
@echo off "%JAVA_HOME%\bin\java.exe" -jar -Xmx128m -Xms64m -XX:MaxPermSize=64m "%~dp0Myfolder\dist\Myjar.jar" %* exit
Perfect if you need to see any console output from your JAR before the window vanishes.
Method 3: Wrap with cmd /c (Universal Fix)
If you want a one-liner that works for both GUI and console apps, wrap your entire Java command with cmd /c. This tells Windows to run the command in a temporary cmd session that closes immediately after completion:
cmd /c "%JAVA_HOME%\bin\java.exe" -jar -Xmx128m -Xms64m -XX:MaxPermSize=64m "%~dp0Myfolder\dist\Myjar.jar" %*
No extra lines needed—this handles both cases smoothly.
Quick Tips:
- Double-check that
%JAVA_HOME%is correctly pointing to your JRE installation path. If it's not set, replace%JAVA_HOME%\bin\java.exewith the full absolute path to your java.exe file (e.g.,C:\Program Files\Java\jre1.8.0_381\bin\java.exe). - If you need to debug temporarily, just remove the
exitcommand to keep the window open after the JAR runs.
内容的提问来源于stack exchange,提问作者nandita

