[java] Creating a batch file, for simple javac and java command execution

It is a really simple thing but I cannot get my head around it. I have looked at plenty of StackOverFlow post and as well as on internet.

My goal is to create a .bat which will open cmd and execute my Main.java into command prompt. Easy isn't it, but I have got confused about how?

Below I am writing steps which my batch file should perform

  1. open cmd
  2. javac Main.java
  3. java Main

My file will reside next to all my .java so I am assuming I don't need to give explicit path.

My understanding so far by research:

  1. open text editor
  2. write a code to open cmd(Which I am not sure how)
  3. echo javac Main.java (Which is still fuzzy concept for me)
  4. echo java Main

Save as: name.bat

Any help will be appreciated. Thank you.

This question is related to java batch-file cmd executable javac

The answer is


Am i understanding your question only? You need .bat file to compile and execute java class files?

if its a .bat file. you can just double click.

and in your .bat file, you just need to javac Main.java ((make sure your bat has the path to ur Main.java) java Main

If you want to echo compilation warnings/statements, that would need something else. But since, you want that to be automated, maybe you eventually don't need that.


you want these four lines of code in your Run.bat:

@echo off          //this makes it so you have an empty cmd window on startup
javac Main.java    //this compiles the .java into a .class
java Main          // this runs the .class file
pause              //this prevents the window from instantly closing after program end

I do not have a JDK installed on my machine to verify this, but here's something to get you started with

%CLASSPATH%=C:\Program Files\Java\jdk1.6\bin rem or whatever your path is
START %CLASSPATH%\javac Main.java
START %CLASSPATH%\java Main

Create a plain text file (using notepad) and type the exact line you would use to run your Java file with the command prompt. Then change the extension to .bat and you're done.

Double clicking on this file would run your java program.

I reccommend one file for javac, one for java so you can troubleshoot if anything is wrong.

  • Make sure java is in your path, too.. IE typing java in a Dos windows when in your java workspace should bring up the java version message. If java is not in your path the batch file won't work unless you use absolut path to the java binary.

I just made a simple batch script that takes a file name as an argument compiles and runs the java file with one command. Here is the code:

@echo off
set arg1=%1
shift
javac -cp . %arg1%.java
java %arg1%
pause

I just saved that as run-java.bat and put it in the System32 directory so I can use the script from wherever I wish.

To use the command I would do:

run-java filename

and it will compile and run the file. Just make sure to leave out the .java extension when you type the filename (you could make it work even when you type the file name but I am new to batch and don't know how to do that yet).


@author MADMILK
@echo off
:getback1
set /p jump1=Do you want to compile? Write yes/no : 
if %jump1% = yes
goto loop
if %jump1% = no
goto getback2
:: Important part here
:getback2
set /p jump2=Do you want to run a java program? Write yes/no : 
if %jump2% = yes
goto loop2
if %jump2% = no
goto getback1
:: Make a folder anywhere what you want to use for scripts, for example i make one.
cd desktop
:: This is the folder where is gonna be your script(s)
mkdir My Scripts
cd My Scripts
title Java runner/compiler
echo REMEMBER! LOWER CASES AND UPPER CASES ARE IMPORTANT!
:loop
echo This is the java compiler program.
set /p jcVal=What java program do you want to compile? : 
javac %jcVal%
:loop2
echo This is the java code runner program.
set /p javaVal=What java program do you want to run? : 
java %javaVal%
pause >nul
echo Press NOTHING to leave

hey I think that you just copy your compiled class files and copy the jre folder and make the following as the content of the batch file and save all together any windows machine and just double click

@echo
setpath d:\jre
d:
cd myprogfolder
java myprogram

  1. Open Notepad

  2. Type in the following:

    javac *
    java Main
    
  3. SaveAs Main.bat or whatever name you wish to use for the batch file

Make sure that Main.java is in the same folder along with your batch file

Double Click on the batch file to run the Main.java file


The only other thing I would add is to make it a tad more flexible. Most times I'll have a trivial java file I want to run like - Main.java, Simple.java, Example.java, or Playground.java (you get the idea).

I use the following to strike off a javac and corresponding java.

@echo off
javac %~n1.java
java %~n1

The %~n1 gets the filename (sans extension) of the first argument passed to the batch file. So this way I can run it using tab completion and not have to worry about it working with either the .class or .java extension.

So both of the following will have the same result:

run.bat Main.class
and
run.bat Main.java

Doesn't 100% answer the original posters question, but I think it is a good next step/evolution for simple javac/java programs.


I've also faced a similar situation where I needed a script which can take care of javac and then java(ing) my java program. So, I came up with this BATCH script.

::  @author Rudhin Menon
::  Created on 09/06/2015
::
::  Auto-Concrete is a build tool, which monitor the file under
::  scrutiny for any changes, and compiles or runs the same once
::  it got changed.
::  
::  ========================================
::  md5sum and gawk programs are prerequisites for this script.
::  Please download them before running auto-concrete.
::  ========================================
::  
::  Happy coding ...

@echo off

:: if filename is missing
if [%1] EQU [] goto usage_message

:: Set cmd window name
title Auto-Concrete v0.2

cd versions

if %errorlevel% NEQ 0 (
    echo creating versions directory
    mkdir versions
    cd versions
)

cd ..

javac "%1"

:loop
    :: Get OLD HASH of file
    md5sum "%1" | gawk '{print $1}' > old
    set /p oldHash=<old
    copy "%1" "versions\%oldHash%.java"

    :inner_loop
    :: Get NEW HASH of the same file
    md5sum "%1" | gawk '{print $1}' > new
    set /p newHash=<new

    :: While OLD HASH and NEW HASH are the same
    :: keep comparing OLD HASH and NEW HASH
    if "%newHash%" EQU "%oldHash%" (
        :: Take rest before proceeding
        ping -w 200 0.0.0.0 >nul
        goto inner_loop
    )

    :: Once they differ, compile the source file
    :: and repeat everything again
    echo.
    echo ========= %1 changed on %DATE% at %TIME% ===========
    echo.       
    javac "%1"
goto loop

:usage_message
echo Usage : auto-concrete FILENAME.java

Above batch script will check the file for any changes and compile if any changes are done, you can tweak it for compiling whenever you want. Happy coding :)


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to batch-file

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH CanĀ“t run .bat file under windows 10 Execute a batch file on a remote PC using a batch file on local PC Windows batch - concatenate multiple text files into one How do I create a shortcut via command-line in Windows? Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat Curl not recognized as an internal or external command, operable program or batch file Best way to script remote SSH commands in Batch (Windows)

Examples related to cmd

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH VSCode Change Default Terminal How to install pandas from pip on windows cmd? 'ls' in CMD on Windows is not recognized Command to run a .bat file VMware Workstation and Device/Credential Guard are not compatible How do I kill the process currently using a port on localhost in Windows? how to run python files in windows command prompt?

Examples related to executable

Running .sh scripts in Git Bash Pyinstaller setting icons don't change How to compile python script to binary executable How can I find out if an .EXE has Command-Line Options? How do I make this file.sh executable via double click? run program in Python shell Running EXE with parameters Creating a batch file, for simple javac and java command execution How can I make a Python script standalone executable to run without ANY dependency? Difference between Groovy Binary and Source release?

Examples related to javac

Setting up enviromental variables in Windows 10 to use java and javac "Javac" doesn't work correctly on Windows 10 Error:java: invalid source release: 8 in Intellij. What does it mean? Javac is not found Maven Unable to locate the Javac Compiler in: Unable to locate an executable at "/usr/bin/java/bin/java" (-1) javac is not recognized as an internal or external command, operable program or batch file javac option to compile all java files under a given directory recursively Creating a batch file, for simple javac and java command execution javac : command not found