A small batch file to compile and execute… Java

My good friend Mark is doing Java. It brings back memories. Great to see that people are still using the command-line to compile and execute Java classes (command-line is back, y'all!).

Entering a javac (compile) and a java (execution) command seems tedious, so I wondered if those could be scripted into a good old .bat file. It has been a while since I've been playing around with batch files. I've seen my father do it... it still looks like a dark - and ancient - art to me.

Batch me!

I've created a file called yall.bat which looks like:

@ECHO OFF

IF '%1'=='' GOTO error
IF NOT EXIST %1 GOTO notfound

ECHO.
ECHO Compiling '%1'...
javac "%~f1"
ECHO done!
ECHO.

ECHO Executing '%~n1':
ECHO.
java %~n1

GOTO end

:error
ECHO.
ECHO Invalid syntax. Please use:
ECHO.
ECHO yall {filename}
GOTO end

:notfound
ECHO.
ECHO File '%1' not found.
GOTO end

:end
ECHO ON

Say what!?

There are some weird variable modifiers that should be explained:

  • %1 is the variable name of the first argument that is passed to the batch script.
  • %~f1 is the first argument turned into a fully qualified file name.
  • %~n1 is the first argument turned into the file name without the extension.

Yep... dark arts indeed. Here is a list of arguments I've found on StackOverflow:

Variable with modifierDescription
%~IExpands %I which removes any surrounding quotation marks ("").
%~fIExpands %I to a fully qualified path name.
%~dIExpands %I to a drive letter only.
%~pIExpands %I to a path only.
%~nIExpands %I to a file name only.
%~xIExpands %I to a file extension only.
%~sIExpands path to contain short names only.
%~aIExpands %I to the file attributes of file.
%~tIExpands %I to the date and time of file.
%~zIExpands %I to the size of file.
%~$PATHSearches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, this modifier expands to the empty string.

Might be handy as a reference for building future batch script (although one ought to move to PowerShell).

Final thoughts

Batch. Still. Cool. Java. Still. Runs.

expand_less