How to include a jar when running a Java file per command line

Asked

Viewed 1,211 times

5

Every time I run the program I need to call a specific library, which in this case is /home/usuario/Programas/weka-x-x-x/weka.jar, but every time I run the program, I have to include the following command java -cp /home/usuario/Programas/weka-x-x-x/weka.jar for libraries to be executed.

I would like to know how to make this library included by default in CLASSPATH, I found this command in Stack Overflow:

export CLASSPATH="dir1;dir2;path/to/jar/containing/AnotherClass;... but it didn’t work.

  • Are you making use of any IDE?

  • No, I use the command line.

1 answer

4


Define libraries without changing Java

It is not recommended to define a classpath global. May cause unwanted side effects in other programs.

To avoid repetition, create a file shell script containing the commands you need, use the chmod to set running permissions for the file and use the new "executable" instead of calling Java directly when you need it.

Using the variable CLASSPATH

If you still want to define a classpath global, the correct is using the environment variable CLASSPATH. However, change the semicolon by colon in the directory separation, as follows:

export CLASSPATH="dir1:dir2:path/to/jar/containing/AnotherClass:...

Semicolon is used in Windows environments while colon is used in Unix/Linux environments.

Also, if you want the environment variable to be present at all linux sessions, even after system reboot, you will need to add the command export in some startup script.

Changing the Java installation

As noted in this reply by Soen, you can put the jar in the folder ext of the Java installation:

JAVA_HOME/jre/lib/ext

Again, I do not advise doing this. Even very common libraries can sometimes generate conflicts. For example, some older project may depend on an older version of the same jar used by a newer application.

  • But I have no way to include this library as a standard in Java to simply no longer need to refer to it? I do something similar in Netbeans, only including in the standard library the jar file.

  • @pmargreff Netbeans is an editor, it will simply automatically add the library to classpath at each execution. I do not consider it correct to add any library directly to the Java installation as it may cause side effects in other programs, but I will update the answer on how you can do this.

  • 1

    Okay, I will consider your suggestion, thank you for the reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.