How to compile and run Java with a single command line on Windows

Every time I want to build and run my program, I:

javac myProgram.java
java myProgram

      

I want to do something like this:

buildrun = javac (some_argument).java && java (some_argument)

      

so after i can just

buildrun myProgram

      

How do I achieve this on Windows?

+3


source to share


2 answers


Like others have suggested, you can simply create a batch file to build and run your program. Copy this to Notepad and save as .bat.

@echo off
set /p class="Enter Class: "
javac "%class%".java
java "%class%"

      



As you wish, the batch file will ask for filename when it starts. In your case, you can set it to "myProgram" and then it will compile and run the program.

Just make sure your batch file and your Java file are in the same folder for this script to run. You can always customize the bat file to even accept the full path of the Java file.

+2


source


Another solution. Create a file buildrun.cmd

with the following code:

@echo off
javac %1.java
if errorlevel = 0 goto RUN

:ERROR
echo "Build fails!"
goto END

:RUN
java %1

:END

      



Now you can pass in the name of the class to be processed. For example: buildrun MyProgram

compile MyProgram.java

and run MyProgram.class

In this case, execution will only be executed if your class was compiled successfully.

0


source







All Articles