You are on page 1of 11

Creating

Java
Executables
Contents :
1. Executable Java Archives
2. The EXE Solution
3. Java Native Interface
Chapter - 1

Executable Java Archives


Introduction

Java applications are generally run using the Java interpreter (“java.exe”) from the Java
Development Kit (JDK). The interpreter is platform-specific and is essential for executing a Java
application. The “java.exe” program interprets the bytecode generated by the compiler. The Java
interpreter is launched from the Windows command prompt in the following form:

java classfilename

In fact, no user would like to enter something like this on the command line to start an
application. What is the solution to this problem? Let(s) try to find out the solution.

In this chapter, you will learn how to create an executable Java archive (jar) file. First, we
will write a small Java program.

File : MyFrame.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

// Class used to show a Frame


public class MyFrame extends JFrame
{
// Constructor
public MyFrame()
{
super("MyFrame");
// Constructs a new TextArea
JTextArea ta = new JTextArea(6,16);
// Set the text of this
// TextComponent to the specified text
ta.setText("\n\n Creating Executable files");

// Set the current font


ta.setFont(new Font("Serif",Font.BOLD+Font.ITALIC,30));
// Set the specified boolean to indicate
// whether or not this TextComponent
// should be editable
ta.setEditable(false);

// Get the content pane object.


getContentPane().add(ta);

// Add the specified window listener


// to receive window events from this window
this.addWindowListener(new WindowHandler());

// Pack the window


pack();

// Set the window visible


show();
}

// Main method
public static void main(String args[])
{
new MyFrame();
}

// Class used to handle window events


private class WindowHandler extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
}

Compiling Class File


The next step is to compile the file just created. I am assuming that the file is
stored in a directory named "myframe". Compile the source file using the command line:

C:\myframe>javac MyFrame.java
The Java Archive Tool

The jar utility is a Java application that combines and compresses multiple files into a
single JAR archive file.

jar [options] [manifest] destination input-file [input-files]

The three types of input files for the jar tool are:
1) manifest file (optional)
2) destination jar file
3) files to be archived

A manifest file is automatically generated by the jar utility. If you want to specify a
manifest file for the new jar archive, you can specify it using the -m option.

Creating Manifest File


Open any text editor like notepad or wordpad and type the following:

Main-Class: MyFrame

A manifest file that you use must end with a new line. The last line of a manifest file will
not be parsed, if it does not end with a new line character.

The Main-Class Attribute


This attribute is used by stand-alone applications that are bundled into executable
jar files, which can be invoked by the Java runtime directly. The value of this attribute defines the
relative path of the main application class that the launcher will load at startup time. The value
must not have the .class extension appended to the class name.

Creating Executable JAR file

C:\myframe>jar cmf MyFrame.mft MyFrame.jar *.class


Options

c - Creates a new or empty archive on the standard output.


f - It specifies a jar file to process. In the case of creation, this refers to the name of the
jar file to be created.
m- Include manifest information from specified pre-existing manifest file.

In this chapter, I have shown you how to create executable Java archives. In the next
chapter, you will learn how to invoke the DOS command interpreter.
Chapter - 2
The .EXE Solution
In this chapter, you will learn how to invoke the DOS command inter-
preter file from a C program.

Execute.cpp

// The #include directive treats


// text in the file specified by
// filename as if it appeared in the
// current file.

#include <alloc.h>
#include <process.h>
#include <stdio.h>

// The #define directive defines a macro.


#define MAIN_CLASS "MyFrame.jar"

int main()
{
// malloc() allocates a block of size
// bytes from the memory heap.
char* cmdline = (char*)malloc(1024 );

// sends formatted output to a string


sprintf( cmdline, "java.exe -jar %s", MAIN_CLASS );

// system() invokes the DOS command interpreter


system( cmdline );

// deallocate the memory


// block.
free (cmdline);
return 0;
}
Explanation

Include necessary header files.

#include <alloc.h>
#include <process.h>
#include <stdio.h>

Actually, your compiler goes through your program several times as it compiles the
program. Before it attempts to translate any code, it simply looks for # signs and makes
any substitutions in the program that are required by the statements that follow.

The #define directive defines a macro. For example:


#define MAIN_CLASS "MyFrame.jar"

The malloc() method allocates a block of bytes from the memory heap. It allows a
program to allocate memory explicitly, as it is needed, and in the exact amounts needed.
The heap is used for dynamic allocation of variable-sized blocks of memory.

char* cmdline = (char*)malloc(1024 );

The sprintf() method is used to send formatted output to a string.

sprintf(cmdline, "java.exe -jar %s", MAIN_CLASS );

The system() method invokes the DOS command interpreter file from inside an executing C
program to execute a DOS command, batch file, or other program named by the string "command".

system( cmdline );

The free() method deallocates a memory block allocated by a previous call to calloc,
malloc, or realloc.

free (cmdline);

Compile "Execute.cpp" using a C\C++ compiler. Use the make command to create the
"Execute.exe". For execution of this application "MyFrame.jar" and "Execute.exe" must
be in the same directory. Under windows, the JRE is installed in the following directory:
Program Files\JavaSoft\JRE\bin
You must set your path to include the "bin" directory.
Open the windows explorer and double click the "Execute.exe" file.rolling on
A console window is required and remains for the life of the Java program. This is fairly
annoying. In the next example, I will solve this problem.

Using javaw.exe

File : Execute1.cpp (Complete code)

// The #include directive treats


// text in the file specified by
// filename as if it appeared in the
// current file.
#include <alloc.h>
#include <process.h>
#include <stdio.h>

// The #define directive defines a macro.


#define MAIN_CLASS "MyFrame.jar"

int main()
{
// malloc() allocates a block of size
// bytes from the memory heap.
char* cmdline = (char*)malloc(1024 );
// sends formatted output to a string
sprintf( cmdline, "javaw.exe -jar %s", MAIN_CLASS );
// system() invokes the
// DOS command interpreter
system( cmdline );
// deallocate the memory
// block.
free (cmdline);
return 0;
}

Compile "Execute1.cpp" using a C\C++ compiler. Use the make command to create the
"Execute1.exe". Open the windows explorer and double click the "Execute1.exe" file. You
will see that no console window appears.
Chapter - 3
Java Native Interface
Java Native Interface is used for writing Java native methods and embedding
the Java virtual machine into native applications.
In this chapter, you will learn how to embed the Java virtual machine into a C program.

File : Test.c (Complete code)

/*The #include directive treats text in the file specified by filename as if it appeared in the
current file.*/
#include <windows.h>
#include <stdio.h>
#include <jni.h>

// The #define directive defines a macro.


#define MAIN_CLASS "MyFrame"
// Entry point
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
JNIEnv* env;
JavaVMOption options[1];
JavaVM* jvm;
JavaVMInitArgs vm_args;
long status;
jclass cls;
jmethodID mainId;
options[0].optionString = "-Djava.class.path=.";
memset(&vm_args, 0, sizeof(vm_args));
vm_args.version = JNI_VERSION_1_2;
vm_args.nOptions = 1;
vm_args.options = options;
/* Create the JVM */
status = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args );
//Error
if( status == JNI_ERR )
return 1;
/*load the class containing the main() method */
cls = (*env)->FindClass( env, MAIN_CLASS );
/* find the main() method */
mainId = (*env)->GetStaticMethodID(
env, cls, "main", "([Ljava/lang/String;)V");
/* call main() */
(*env)->CallStaticVoidMethod(env, cls, mainId, 0);
/* kill the JVM */
(*jvm)->DestroyJavaVM( jvm );
return 0;
}

Explanation

The JNIEnv type is a pointer to a structure storing all JNI function pointers. The env
pointer is the first argument of every native method.
The JNI_CreateJavaVM() function loads and initializes a Java VM and fills in a pointer jvm
to virtual machine and a pointer env to the execution environment.
The FindClass() method is used to load a class.
The GetStaticMethodID() returns the identifier of a static method in a class.
The CallStaticVoidMethod() calls the main method of the MyFrame class.
The DestroyJavaVM() method unloads a Java virtual machine and reclaims resources

Compiling the Program

To compile this program, you need Microsoft Visual C++ compiler. Use the following
command line to compile the program.
cl -Ic:\jdk\include -Ic:\jdk\include\win32 Test.c c:\jdk\lib\jvm.lib.

If you are unable to compile then, set the path and environment variables by running the follow-
ing file: devstudio\vc\bin\vcvars32.bat

You might also like