简体   繁体   中英

Need help running my Java .jar file from Windows batch file

I have a Java jar file located in:

C:\Users\myusername\bin\MyDir\MyApp.jar

I also have some required properties files (needed as input arguments to the .jar file) located in the same directory as the .jar file.

I created a runme.bat file here:

C:\Users\myusername\Desktop\runme.bat

In the runme.bat file, this is what I have:

setlocal
set JAVA_HOME="C:\Program Files\Java\jdk1.8.0_161\bin\"
set PATH=C:\Users\myusername\bin\MyDir\
start %JAVA_HOME%javaw -jar %PATH%MyApp.jar %PATH%propertiesfile.properties

However, whenever I try to run the .bat file, I get the error:

Windows cannot find '-jar' Make sure you typed the name correctly, and then try again.

On the command line I see Windows trying to do this:

> "C:\Program Files\Java\jdk1.8.0_161\bin\"javaw -jar C:\Users\myusername\bin\MyDir\MyApp.jar ...

I get this error when running from the command line. If I simply double-click the .bat file, a cmd window comes up and quickly disappears.

So, what am I doing wrong?

Thanks!

Use Double quotes around the set command, not inside the variables.

Also, I see no reason to use the START command unless you want to do more in your batch file in the original command prompt after starting your Java in a second command prompt. Possible but seems unlikely.

Generally, you will just type in the executable or use CALL so that the executable runs and control returns to the batch after reaching conclusion.

Additionally, you changed your system path variable to be just the path of your java files which will make the session pretty screwy. Thankfully this should only persist in your open command windows and those spawned by the original window, so close them all and then use a different variable name for your path.

So I will put this both ways, using Call, and using start.

Here is your code using call:

@(
    setlocal
    ECHO ON
)

set "_Title=Runnning My Java"
set "JAVA_HOME=C:\Program Files\Java\jdk1.8.0_161\bin"
set "_MyJarPath=C:\Users\%UserName%\bin\MyDir"

TITLE "%_Title%"
CD /D "%JAVA_HOME%"
CALL "%JAVA_HOME%\javaw.exe" -jar "%_MyJarPath%\MyApp.jar" "%_MyJarPath%\propertiesfile.properties"

(
    ENDLOCAL
    EXIT /B 0
)

Here is your code using the start command:

@(
    SETLOCAL
    ECHO ON
)

set "_Title=Runnning My Java"
set "JAVA_HOME=C:\Program Files\Java\jdk1.8.0_161\bin"
set "_MyJarPath=C:\Users\%UserName%\bin\MyDir"

start "%_Title%" /D "%JAVA_HOME%" "%JAVA_HOME%\javaw.exe" -jar "%_MyJarPath%\MyApp.jar" "%_MyJarPath%propertiesfile.properties"

(
    ENDLOCAL
    EXIT /B 0
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM