Windows find java library path

java.library.path – What is Java library and how to use

Posted by: Bhagvan Kommadi in Java Basics March 4th, 2014 3 Comments Views

In this tutorial, we will discuss how to set java.library.path. We will explain its definition, and how can be used by Java applications.

The Java Virtual Machine (JVM) uses the java.library.path property in order to locate native libraries. This property is part of the system environment used by Java, in order to locate and load native libraries used by an application.

When a Java application loads a native library using the System.loadLibrary() method, the java.library.path is scanned for the specified library. If the JVM is not able to detect the requested library, it throws an UnsatisfiedLinkError . Finally, the usage of native libraries makes a Java program more platform dependent, as it requires the existence of specific native libraries.

1. What is a java library and why we use it?

A java library consists of software components that are developed by programmers and reusable. They help in providing different services. A java library is in a deployment format called JAR file. The format is based on pkzip file format. A jar file has java classes and resources such as properties, icons, and other files. A java library file can be used in other Java projects by specifying it in the classpath. The classes in the jar file are accessible to java application after the library is specified in the classpath.

2. How to find a library jar and download it?

A java library can be searched in different repositories such as maven, guava, apache-commons, and others. You can download the java library by specifying the version from these repositories. The java library is specified in the classpath and classes from the library are used in java projects. For example, the database driver libraries can be downloaded from the database vendor repositories. Postgres SQL will be available on the PostgreSQL website.

3. How to set the java.library.path property

There are several ways to set the java.library.path property:

    Through the command line or terminal: Using the terminal (Linux or Mac) or the command prompt (Windows), we can execute the following command, in order to execute our Java application:

where the path_to_dll argument must be replaced with the path of the required library.

Through Java source code: Inside an application’s code we can set the java.library.path using the following code snippet:

4. Setting the java.library path. using Eclipse

In order to define the java.library.path property in Eclipse , the following steps must be completed:

  • Select your project in the Package Explorer area and press a right-click on it.
    1. Select Build Path → Configure Build Path. option.
    2. In the appearing window, select the Libraries tab.
    3. Then, expand the JRE System library option and select the Native library location .
    4. Click on the Edit. button at the right panel.
    5. Locate the required library and then click OK .
    6. Close the window.
Читайте также:  Astra linux как сделать пользователя администратором

If the aforementioned steps have been successfully completed, then the selected project will be executed using the required native library.

5. Setting the java.library path. using Netbeans

In order to define the java.library.path property in Netbeans , the following steps must be completed:

  • Select your project in the Projects area and press a right-click on it.
  • Select Properties and then, move to the Run tab.
  • In the VM Options field, add the following option, based on your library’s path:
    java -Djava.library.path=
  • Click on OK in order for the window to close.
  • If the aforementioned steps have been successfully completed, then the selected project will be executed using the required native library.

    6. Top 10 Java standard libraries

    Top 10 Java standard reusable libraries are mentioned below:

    • Core Java Libraries
      • java.lang
      • java.util
      • java.io
      • java.nio
      • java.math
      • java.net
    • Java UI Libraries
      • javax.swing
    • java.media
    • Apache Commons
      • commons.math
      • commons.cli
      • commons.csv
      • commons.io
    • spring boot
    • google-gson
    • hibernate-orm
    • Unit Testing Libraries
      • mockito
      • junit
    • log4j
    • Slf4j

    7. Create an example in which you use a library

    Let us look at creating a Math Library with public api with methods for product and difference of two integers. MathAPI class is shown as below:

    The command used for compilation of the code in the math folder is shown below:

    Java library MathAPI.jar is created by using the following command:

    The MathAPI library can be used in MathAPIExample as shown below:

    The command used for compilation of the code is shown below:

    The command used for execution of the code is shown below:

    The output of the above command when executed is shown below:

    8. Download the Source Code

    That was an article about java.library.path: What is Java library and how to use.

    Last updated on Oct. 06th, 2020

    Can I find out what variable java.library.path maps to on the current platform?

    So far I’ve learned the following about the java.library.path property:

    • It’s used when loading native libraries, as opposed to java classes
    • Its default value depends on the operating system:
      • On Windows, it maps to PATH
      • On Linux, it maps to LD_LIBRARY_PATH
      • On OS X, it maps to DYLD_LIBRARY_PATH

    (Please correct me if I’ve misunderstood any of the above)

    I want to modify the value of java.library.path seen by a Java application from the framework I’ve set up to invoke the Java application. I want to do this not by setting the java.library.path property directly, but instead by modifying the system path variable that it maps to. I’d like a clean way to do this that doesn’t have ugly OS-specific code or leave out edge cases if possible.

    Is there a way to ask the local Java implementation what environment variable java.library.path maps to?

    Then, in a shell script, I’d be able to write something along the lines of:

    2 Answers 2

    This isn’t a totally unreasonable question, but there’s no good answer, so for posterity, I’ll make an attempt at explaining why you got stuck, and why it won’t work.

    java.library.path isn’t guaranteed to be set from an environment variable at all. You can specify what you want it to be with -Djava.library.path= . More than likely, this is what you really want to do anyway. That’s why the option exists.

    Читайте также:  Windows брандмауэр закрыть порты

    It turns out (on windows at least), that the environment variable you’re looking for isn’t just used unmolested. Try this code.

    Find absolute java.exe path programmatically from java code

    If I have a java jar or class file which is launched by the user (assuming java path is set in environment variables), so how can i from within the code, figure out absolute path of java.exe/javaw.exe from which this file is being launched.

    Like on ubuntu we can run: % which java and it shows the path.

    However on windows, if i check System.getenv() it may happen that there are multiple path’s found e.g for old or new version. If through cmd line, I run java -version it does not show the path.

    Can you tell me either through pure java or command line on windows how is it possible to find out the location of javaw.exe?

    3 Answers 3

    Can you tell me either through pure Java . on windows how is it possible to find out the location of javaw.exe?

    Output

    And yes, I am confident that will work in a JRE.

    On Windows, the java.library.path System Property begins with the path to the bin directory containing whichever java.exe was used to run your jar file.

    This makes sense, because on Windows the first place any executable looks for DLL files is the directory containing the executable itself. So naturally, when the JVM runs, the first place it looks for DLLs is the directory containing java.exe.

    You can acquire the path to java.exe as follows:

    This code is Windows-specific — I hard-coded the path separator (;) and the file separator (). I also put in a fallback to just «java» in case the library path trick somehow doesn’t work.

    I have tested this with Java 6 and 7 on Windows 7. I tried a 32-bit and 64-bit version of Java.

    JNI, загрузка нативных библиотек. Меняем java.library.path на лету

    В подмножестве экосистемы Java, относящейся в основном к JNI (без которого никуда не деться, если приходиться интегрироваться с каким-то legacy или просто редким и специфическим кодом, написанном на С или каком-то другом языке), есть такое понятие, как java.library.path. Вкратце, это в некотором роде аналог classpath, только не для Java классов и *.jar файлов, а для нативных библиотек — системное свойство, которое указывает JVM, где искать эти самые нативные библиотеки (.dll в винде или .so под юниксами).

    Свойство это устанавливается один раз, перед запуском JVM, через глобальные system properties, или как ключ -Dname=value для JVM, и после этого оно становится read-only. Точнее, менять-то его можно, но никакого эффекта на работу программы это не окажет, т.к. после того как вы обновите это свойство, JVM не перечитает его и не будет использовать новое значение.

    Под катом — про то, как все таки поменять это свойство в рантайме, и немного о том, как собственно работает загрузка нативных библиотек в Java.

    Однако, возможность менять java.library.path на лету была бы очень кстати — тогда бы не пришлись много раз генерить, переписывать и перезаписывать скрипты для запуска JBoss-a, например, чтобы отразить в них все нужные пути ДО старта аппсервера.

    И такая возможность, изменять эти пути, по которым JVM ищет нативные библиотеки, на самом деле есть. Конкретные приемы показаны тут — blog.cedarsoft.com/2010/11/setting-java-library-path-programmatically и еще вот тут — nicklothian.com/blog/2008/11/19/modify-javalibrarypath-at-runtime.

    А здесь я опишу сам механизм загрузки, и почему то, что описано по ссылкам, работает. Обычно, нативные библиотеки загружаются через статический инициализатор:

    Читайте также:  Windows 10 восстановление системы не работает пуск

    * This source code was highlighted with Source Code Highlighter .

    Который выглядит так:

    public static void loadLibrary( String libname) <
    Runtime.getRuntime().loadLibrary0(getCallerClass(), libname);
    >

    * This source code was highlighted with Source Code Highlighter .

    И далее в классе Runtime:

    synchronized void loadLibrary0(Class fromClass, String libname) <
    // Проверяем, разрешено ли загружать данную конкретную библиотеку
    SecurityManager security = System.getSecurityManager();
    if (security != null ) <
    security.checkLink(libname);
    >
    if (libname.indexOf(( int ) File .separatorChar) != -1) <
    throw new UnsatisfiedLinkError( «Directory separator» +
    «should not appear in library name: » + libname);
    >
    ClassLoader.loadLibrary(fromClass, libname, false );
    >

    * This source code was highlighted with Source Code Highlighter .

    Т.е. в итоге, нативные библиотеки загружаются, так же как и обычные классы, через ClassLoader. У класса ClassLoader есть два свойства, в которых кешируются проинициализированные пути поиска.

    // The paths searched for libraries
    static private String usr_paths[];
    static private String sys_paths[];

    * This source code was highlighted with Source Code Highlighter .

    Код метода ClassLoader.loadLibrary(fromClass, libname, false), довольно длинный, и загроможденный многочисленными проверками, в сокращенном виде выглядит это так.

    // Invoked in the java.lang.Runtime class to implement load and loadLibrary.
    static void loadLibrary(Class fromClass, String name,
    boolean isAbsolute) <

    ClassLoader loader = (fromClass == null ) ? null : fromClass.getClassLoader();
    if (sys_paths == null ) <
    // это то, что нам нужно
    usr_paths = initializePath( «java.library.path» );

    // а это для тех библиотек, которые загружаются из классов,
    // загруженных из boot classpath.
    sys_paths = initializePath( «sun.boot.library.path» );
    >

    // Дальше попытка загрузить библиотеку, и дальше,
    // если найти ее так и не удалось, то —
    // Oops, it failed
    throw new UnsatisfiedLinkError( «no » + name + » in java.library.path» );
    >

    * This source code was highlighted with Source Code Highlighter .

    Таким образом, теперь механизм загрузки нативной библиотеки стал более понятен.

    Вы можете либо выставить в null свойство sys_paths у класслоадера, либо просто поменять свойства sys_paths / usr_paths, добавив к ним нужные пути к вашим нативным библиотекам.

    Java error — cannot find library in java.library.path?

    I am getting a error message like this:

    The library libraryname.dll could not be loaded by Windows. Make sure that the library is in you Path environment variable. Exception in thread «main» java.lang.UnsatifiedLinkError: no libraryname in java.library.path.

    This error is from me trying to run a jar file on Windows XP via cmd. I am wondering, where exactly is java.library.path? I’ve already added C:\Program Files\Java\jdk1.6.0_26 to my PATH but it still gives me the error. How would you go about debugging this?

    2 Answers 2

    You can simply pass java.library.path as a system property as shown below:

    First you need to find out where the libraryname.dll is and add it above in «path_to_dll».

    The error is basically saying it cannot find your native libraries. Java tries to locate your library by looking into java.library.path property

    It’s an System environment that you need so Java can find your native libraries when you run your application. Several ways to do it:

      Use java -Djava.library.path=[path to your library] when running your program

    From the code you could also do.

    Set it up from your IDE. An example for Eclipse can be found in this SO question How to set java.library.path from eclipse

    EDIT: A good comment below pointed out that #2 will not working 100% because you might not set this prior to calling getProperty(). Missed that point and thanks for pointing that out.

    Оцените статью