Vítor Amesa
Vítor Amesa

Reputation: 43

How to compile java in Vim

I can compile the same code in cmd, so my environment variables are right, but in Vim i get this:

error: file not found: Test.java
Usage: javac <options> <source files>
use --help for a list of possible options

shell returned 2

I'm using :!javac Test.java to compile.

This is my code:

public class Test{
    public static void main(String[]args) {
        System.out.println("Hello World");
    }
}

If anyone can help me, thank you very much.

Upvotes: 2

Views: 966

Answers (1)

Doj
Doj

Reputation: 1311

The problem is that you got undesirable current directory (a.k.a. working directory) of your vim session. You can check it with :pwd and it should print the directory of the Test.java file.

There is :cd {path} command which changes current directory, and you can change the current directory to the directory of the current file with :cd %:h. After that javac should find the Test.java file.

There are several ways to avoid manually calling :cd %:h every session:

  1. Run gvim via context menu (right click on a file, Edit with Vim or something like this), this way the current directory will be the directory of the opened file.

  2. Run gvim from a terminal: gvim Test.java. As in previous suggestion the current directory will be the directory of the opened file.

  3. Add the following line to your .vimrc / _vimrc file:

autocmd BufRead,BufNewFile * cd %:h

With this command the cd %:h will be run automatically every time you open a file inside gvim.

Upvotes: 4

Related Questions