|
Converting Java code into a Windows EXE file |
|
Wednesday, 04 July 2007 00:00 |
|
My most recent project involved putting together a client-side tool
that would help upload files to my web site. Being a Java developer, I
knew it would be very easy to code this with minimal effort needed to
support I/O, network, and SSL. However, I wanted to be able to provide
my clients with a stand-alone executable.
I'm sure that the best
approach would be to develop this tool in another language (such as
C/C++), but felt this would be a big learning curve for me. Instead, I
quickly searched Google to see if there was a way to compile Java code
into a native Windows binary. I found that there are definitely tools
out there that can help do this, but it took some time to research and
figure out how to get it all working.
So here are the steps I eventually figured out in order to compile Java code into a Windows EXE file:
Step 1 I found this site that provides a pre-compiled version of the GNU Java compiler: http://www.thisiscool.com/gcc_mingw.htm
I scrolled down to GCC/GCJ 4.02,
where it says "The Bundle", and download the .tar (similar to .zip)
file. The file was about 64MB. (Note: The file download had a .bz2 file
extension, but my browser seemed to automatically rename it to .tar)
Step 2 Extract
the .tar file to a directory of your choosing. You should be able to
use a tool such as WinZip or 7-Zip to extract .tar files.
Step 3 Open
a command prompt window and navigate to the directory where the files
are extracted. Go into the "gcc-4.0\bin" directory. Run this command to
compile you Java file(s) into an EXE file: gcj --main=com.package.name.ClassName ClassName1.java ClassName2.java ClassName3.java ...
Note
that you will need to use the proper path for each java file you'd like
to compile. Also note that you will need to list out each Java file
that is a dependency of the main class. I believe you can also set your
classpath in an environment variable, but I had some issues doing this
because it seems that gcj does not currently support Java 1.5+.
Step 4 This
command should generate a file named a.exe, which you can then rename
to anything you'd like. You should now be able to execute your Java
code as a stand-alone program!
So far, I have only built a
simple "Hello World" program to test it out. I'm not too sure how well
it will support GUIs (such as Swing), but it seems that it should work
pretty well for command-line programs.
Lastly, it's worth
mentioning that the .exe file that is generated will be pretty big. The
simple "Hello World" program was over 2MB in size. It seems that
compiling Java into a native binary will always have a certain amount
of overhead, due to the garbage collector and other aspects of
management that Java performs for you.
|