Java System.load() – Examples
In this tutorial, we will learn about the Java System.load() function, and learn how to use this function to load a native library into System, with the help of examples.
load(String filename)
System.load() loads the native library specified by the filename
argument.
The filename
must be an absolute path to the file you would like to load.
Syntax
The syntax of load() function is
load(String filename)
where
Parameter | Description |
---|---|
filename | Absolute path of the file to load. |
Returns
The function returns void.
Example 1 – load(String filename)
In this example, we will load a .dll
file. Absolute path of the file is given to load() method as argument.
Java Program
public class Example {
public static void main(String args[]) {
System.out.println("Loading dll..");
String filename = "C:\\Users\\TutorialKart\\.eclipse\\org.eclipse.platform_4.4.1_1845977472_win32_win32_x86_64\\configuration\\org.eclipse.osgi\\86\\0\\.cp\\os\\win32\\x86_64\\localfile_1_0_0.dll";
System.load(filename);
System.out.println("Loading finished.");
}
}
Output
Loading dll..
Loading finished.
Example 2 – load(String filename) – File Path Incorrect
In this example, we will provide an incorrect path as filename
to load() method. load() method should throw java.lang.UnsatisfiedLinkError
.
Java Program
public class Example {
public static void main(String args[]) {
System.out.println("Loading dll..");
String filename = "C:\\nothing.dll";
System.load(filename);
System.out.println("Loading finished.");
}
}
Output
Loading dll..
Exception in thread "main" java.lang.UnsatisfiedLinkError: Can't load library: C:\nothing.dll
at java.base/java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.base/java.lang.Runtime.load0(Unknown Source)
at java.base/java.lang.System.load(Unknown Source)
at Example.main(Example.java:6)
Example 3 – load(filename) – Null filename
In this example, we will provide a null
value as filename
to load() method. load() method should throw java.lang.NullPointerException
.
Java Program
public class Example {
public static void main(String args[]) {
System.out.println("Loading dll..");
String filename = null;
System.load(filename);
System.out.println("Loading finished.");
}
}
Output
Loading dll..
Exception in thread "main" java.lang.NullPointerException
at java.base/java.io.File.<init>(Unknown Source)
at java.base/java.lang.Runtime.load0(Unknown Source)
at java.base/java.lang.System.load(Unknown Source)
at Example.main(Example.java:6)
Conclusion
In this Java Tutorial, we have learnt the syntax of Java System.load() function, and also learnt how to use this function with the help of examples.