I've started using vim recently as my main text editor and I've tried to come up with a map command which compiles and runs my java source code.

This is what I have so far:
map <F4> :!javac % <CR>:!java %< <CR>

but it doesn't always work. For example, when The folder name is the same as the .java/.class file, I will get a 'ClassNotFound' error (which runs fine if I do it through a terminal). There are also other problems with spaces in the path name.

Does anybody have a mapping that works properly with compiling and running java source files?

I seem to have found out what was wrong. After doing some searches for the error messages I have been receiving, it seems that since I was executing the file from a directory other than the working directory, I had to specify the location of the classpath to the java VM. (I'm guessing by default, java looks in the current working directory for classes)

I have updated my .vimrc to look like this:

" java compile
map <F3> :call CompileJava()<CR>

func! CompileJava()
	:!javac "%"

" run class
map <F4> :call RunClass()<CR>

func! RunClass()
	:!java -cp "%:p:h" "%:t:r"

and for gVim (windows) I had to enclose the entire command in quotes since gVim passes the command to cmd /c :

:!""C:\Program Files\Java\jdk1.6.0_18\bin\javac.exe" "%""

I have the entire path because I use gVim at school and I have to add the JDK folder to the path every reboot (they use DeepFreeze which resets any changes to machines at reboot).

"%" by itself is the file you're editing in Vim and the path to it
eg. /path/to/file/File.java
(I've surrounded it in quotes in case there are spaces in the file name or path)

:!java -cp "%:p:h" "%:t:r"
the -cp flag specifies the folder in which the class file can be found
"%:p:h" is just the path to the file you're editing in Vim
the final parameter in the command is the file itself
"%:t:r" means the file name, without the path or the file extension

So in the terminal, vim ends up running:
java -cp /path/to/file/ File
which runs the class file.

Hope this helps.

Hmm, for some reason the text within the

tags shows up as Java syntax...[code]
tags shows up as Java syntax...

This question has already been answered. Start a new discussion instead.