Wednesday Nov 28, 2007

A simple example of JNI

Java Native Interface (JNI) is a standard programming interface for writing Java native methods and embedding the JVM into native applications. Simply, it is a Java technology with which a Java application can call a method written with such as C, C++ and assembly.

Adopting JNI is very simple. You need two components -- a Java program, and a native library. The native library is written in other languages and compiled on corresonding platforms.

A function defined in the native library should be declared in Java code as a 'native' function. And the native library needs to be load in Java code with the System.loadLibrary method. The natvie function could be referced by other regular functions in the Java code.

Following is an example of the Java Code.

public class JNIFoo {    
    public native String nativeFoo();    

    static {

    public void print () {
    String str = nativeFoo();
    public static void main(String[] args) {
    (new JNIFoo()).print();

# javac
# javah -jni JNIFoo

A file named as JNIFoo.h is created by running the above two commands. A function of 'JNIEXPORT jstring JNICALL Java_JNIFoo_nativeFoo  (JNIEnv \*, jobject)' is in the JNIFoo.h file. The function must be implemented in a source code file (e.g. a C file), and it is the actually entry to do what the funtion of natvieFoo() in Java code do.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <jni.h>
#include "JNIFoo.h"

JNIEXPORT jstring JNICALL Java_JNIFoo_nativeFoo (JNIEnv \*env, jobject obj)
  int i;
  int ds_ret;

  char\* newstring;

  jstring ret = 0;

  newstring = (char\*)malloc(30);

  if(newstring == NULL)
      return ret;

  memset(newstring, 0, 30); 
  newstring = "foo: Test program of JNI.\\n";

  ret = (\*env)->NewStringUTF(env, newstring);


  return ret;

JNI libraries are named with the library name used in the System.loadLibrary method of your Java code with a prefix and a suffix. On different OS, the prefix and suffix might be different.

On Solaris OS, it is prefixed by 'lib' and suffixed with '.so'

# cc -Kpic -G -o -I/usr/java/include -I/usr/java/include/solaris foo.c -z text

On Linux OS, it is prefixed by 'lib' and suffixed with '.so'.

# gcc -shared -fpic -o -I/usr/java/include -I/usr/java/include/linux foo.c

On Windows OS, it is prefixed by nothing and suffixed with '.dll'.
It could be compiled with Visual Studio automatically and create a file named as foo.dll.

On Mac OS, it is prefixed by 'lib' and suffixed with '.jnilib'.

# gcc -dynamiclib -o libfoo.jnilib -I/System/Library/Frameworks/JavaVM.framework/Headers foo.c -framework JavaVM


To run the JNI program locally, the following command is fine:

# java -Djava.library.path=<path_of_native_lib> JNIFoo 

Tuesday Nov 27, 2007

Bundle an executive binary program with a Java Web Start application

When an Java application needs to call native program(s) to handle situations, JNI is frequently the preferred technology.

If the Java application is deployed with Java Web Start. The embedded native program could be packaged in a jar file, and the jar is deployed as a native library of the Java application.

Following is a piece of JNLP file. It is obvious that the foo.jar is the Java application, and the libfoo.jar including a native program which normally should be an shared object (e.g. on Unix-like OS or foo.dll on Windows OS).



    <j2se version="1.4+" java-vm-args="-client"/>

    <jar href="/foo.jar" main="true" download="eager"/>

    <nativelib href="/libfoo.jar"/>



However, sometimes a shared object doesn't meet our requirement. For example, an executive program is always much smaller rather than a dynamic-link library. Considering to reduce launch time, we prefer to bundle an exe file with our JavaWS application instead of a DLL file.

Technically we can bundle any files that we want in our application JAR. The executive binary program could also be packaged in a JAR file. But the methods in the native program cannot be referenced by the Java application directly. In such scenario, the JNI is inapplicable.

The executive program should be executed on users' system, and interface between it and the Java application is its out put message.

Although, it is possible to reference to the contents of the Java Web Start cache directly. We don't recommend it, since the cache is a private implementation of Java Web Start, and is subjected to change anytime.

The URL returned for calls to ClassLoader.getResource() is now the proper JAR URL of the item on the net. (, see bullet item related to "Jar Indexing")

We could to access the EXE in the JAR by using a JarURLConnection to get to the resource. e.g ,

| jar:!/foo.exe |

We can then get the InputStream of the binary program, and then copy it to a temp location on disk, and then execute it from there.

If the JAR resource is already cached, the contents of the resource will be returned from the cache directly, so there won't be extra network connections to the JAR itself.

NOTE: This solution is only applicable with JVM 1.6.

Following is an example of such an implementation.

File of


... ...

   private String execute() throw IOException {   

    ... ...

    ClassLoader loader = this.getClass().getClassLoader();

    /\* jnitest is an binary program running on Solaris OS.

        It is packaged in a Jar file of libjnitest.jar \*/

    URL url = loader.getResource("jnitest");                           

    /\* Note: the size of the buffer must not less than the size of jnitest \*/

    byte[] buf = new byte[20000];

    int len = 0;

    JarURLConnection uc = (JarURLConnection)url.openConnection();             


    InputStream in = new BufferedInputStream(uc.getInputStream());

    len =;


    File tmpFile = new File(fileName);           

    FileOutputStream output = new FileOutputStream(tmpFile);

    output.write(buf, 0, len);  


    runCommand("chmod +x " + fileName);

    /\* Execute the executive native program, and get its output message \*/

    String outputMessage = runCommand(fileName);            

    return outputMessage;


    private String runCommand(String command) {

        String[] cmd0 = {"sh", "-c", command};

        try {

                Process ps = Runtime.getRuntime().exec(cmd0);

                String str1 = loadStream(ps.getInputStream());

                return str1;

        } catch (IOException ioe) {

                System.err.println("Error: running command on Solaris OS failed.");

        return null;


    private String loadStream(InputStream input) throws IOException {

        int count;

        int BUFFER = 20;

        byte[] data = new byte[BUFFER];

        input = new BufferedInputStream(input);

        StringBuffer buff = new StringBuffer();

        while ((count =, 0, BUFFER)) != -1)

            buff = buff.append(new String(data, 0, count));

        return buff.toString();


... ...

File of testfoo.jnlp


... ...


    <j2se version="1.4+" java-vm-args="-client"/>

    <jar href="/testfoo.jar" main="true" download="eager"/>   

    <nativelib href="/libjnitest.jar"/>


... ...


Ye Julia Li


« July 2016