Vim Tips for Java #1: Build Java files with Ant automatically

Ant is a great tool for compiling large projects with a large number of Java files. It is the equivalent of 'make' for C, but is customised specifically for Java. While the support for make works with vim by default, certain changes have to be made for vim in order to make it work properly for Java.

Add the following lines in your .vimrc:

autocmd BufRead *.java set efm=%A\ %#[javac]\ %f:%l:\ %m,%-Z\ %#[javac]\ %p^,%-C%.%#
autocmd BufRead set makeprg=ant\ -find\ build.xml

As long the build.xml file is in the parent directory of where the Java files you are working on is located, vim will be able to locate it, compile the changed files and inform you of where the compilation errors are.

All that’s remaining is just to type :make, and you now have automatic compilation from within Vim!

If you like reading this, you may also enjoy: