Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to run a small/medium java program from the command line?

Tags:

java

linux

ant

Coming from a c++/make background, I'm used to doing something like this to build and run small/medium programs:

make
./foobar

However, with java/ant I'm finding I have to do something like this:

ant
java -ea -cp build/ foobar

Typing out java -ea -cp build/ foobar every time I want to test my program is pretty annoying, I'd much rather be able to do something simple like ./foobar.

I came up with two possible solutions to this problem, but neither seems very good. The first is to just have the compile target create a file called run:

#!/bin/bash

java -ea -cp build/ foobar

And then just use ./run to run the program, however this seems to go against ant's cross-platform nature, and also just seems like a bit of a hack.

The second option is to create a run target, for example:

<target name="run" depends="compile">
   <java classname="foobar" fork="true">
      <classpath>
         <pathelement path="${build}"/>
         <pathelement path="${java.class.path}"/>
      </classpath>
      <assertions>
         <enable/>
      </assertions>
   </java>
</target>

This method also works, and seems a bit cleaner, but is incredibly slow! For example:

$ time ant run
Buildfile: /somepath/build.xml

init:

compile:

run:
     [java] /* program output */

BUILD SUCCESSFUL
Total time: 1 second

real    0m2.683s
user    0m2.548s
sys     0m0.136s

The above is almost 20 times slower (!) than this:

$ time ./run
/* program output */

real    0m0.143s
user    0m0.124s
sys     0m0.020s

So is there a better/more standard way of running a small/medium java program from the command line? Or should I just use one of the methods I posted here?

like image 344
Gordon Bailey Avatar asked Mar 16 '26 02:03

Gordon Bailey


1 Answers

It seems to me you want to build/run during development phase.

If so, then get an Eclipse and use it to debug/run, it's the most effective way of developping under java.

Usually:

  • Ant is used for packaging phase

  • shell is used for running program, and you would write one per environment (Linux/Windows/Mac OS)

like image 165
UBIK LOAD PACK Avatar answered Mar 18 '26 16:03

UBIK LOAD PACK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!