Java Reference
In-Depth Information
E.2
Creating executable .jar files
Java projects are typically stored as a collection of files in a directory (or “folder”). We shall
briefly discuss the different files below.
To distribute applications to others, it is often easier if the whole application is stored in a single
file. Java's mechanism for doing this is the Java Archive (
.jar
) format. All of the files of an
application can be bundled into a single file, and they can still be executed. (If you are familiar
with the “zip” compression format, it might be interesting to know that the format is, in fact, the
same. “Jar” files can be opened with zip programs and vice versa.)
To make a
.jar
file executable, it is necessary to specify the
main
class somewhere.
(Remember: The executed method is always
main
, but we need to specify the class this method
is in.) This is done by including a text file in the
.jar
file (the
manifest file
) with this informa-
tion. Luckily, BlueJ takes care of this for you.
To create an executable
.jar
file in BlueJ, use the
Project—Create Jar File
function, and
specify in the resulting dialog the class that contains the main method. (You must still write a
main method exactly as discussed above.)
For details with this function, read the BlueJ tutorial, which you can get through the BlueJ menu
Help—Tutorial
or from the BlueJ web site.
Once the executable
.jar
file has been created, it can be executed by double-clicking it. The
computer that executes this
.jar
file must have the JDK or JRE (Java Runtime Environment)
installed and associated with
.jar
files.
E.3
Developing without BlueJ
If you want not only to execute but also develop your programs without BlueJ, you will need to
edit and compile the classes. The source code of a class is stored in a file ending in
.java
. For
example, class
Game
is stored in a file called
Game.java
. Source files can be edited with any
text editor. There are many free or inexpensive text editors around. Some, such as
Notepad
or
WordPad
, are distributed with Windows, but if you really want to use the editor for more than
a quick test, you will soon want to get a better one. Be careful with word processors, though.
Word processors typically do not save text in plain text format, and the Java system will not be
able to read it.
The source files can then be compiled from a command line with the Java compiler that is in-
cluded with the JDK. It is called
javac
. To compile a source file named
Game.java
, use the
command
javac Game.java
This command will compile the
Game
class and any other classes it depends on. It will create
a file called
Game.class
. This file contains the code that can be executed by the Java virtual
machine. To execute it, use the command
java Game
Note that this command does not include the
.class
suffix.
Search WWH ::
Custom Search