Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The easiest way to run java class when editing the .java file form VIM

Tags:

java

terminal

vim

If I'm coding in cpp, in Vim I can do:

!g++ % && ./a.out

to quickly compile and run the code.

However, if I'm coding in Java, in Vim I can do:

!javac %

for a quick compilation, but for running the java class, I cannot do:

!java %

because I need to put the class name only (without the trailing .java suffix)

Is there a quick way in VIM to do what I did when I was coding in Cpp?

Thanks a lot.

like image 369
songyy Avatar asked Feb 23 '13 02:02

songyy


People also ask

Can I run Java in Vim?

JavaRun - Compile and run Java program : vim online. Save/compile (if necessary) and run the Java, Python, Perl, Ruby, Tcltk or CLisp source program in the current buffer. Some useful abbreviations for Java programming, e.g. psvm for "public static void main(String[] args) { }", cl for class, etc.

How do I run a Java program from a file?

Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.


1 Answers

Vim has modifiers with which you can manipulate filenames. For your use case, the :r modifier returns the root, i.e. the file name with the last extension removed:

:!java %:r

See the full list at :help filename-modifiers; they also can be combined. Note that for more complex builds, a Java build solution like Ant or Maven is probably more effective; these can also be launched from Vim; even integrated into its :make command.

like image 182
Ingo Karkat Avatar answered Sep 22 '22 11:09

Ingo Karkat