Create Jar File Programmatically

Java archive (jar) files are compressed files that can store one or many files in a single file, which normally contain java or class files, but other files may also be included. Jar files used to distribute Java applications and libraries too.

You can easily create jar file in windows environment using the command prompt. Follow the link to see how to create a jar file.

In this example I will show you how create jar file from your java application. To create the jar file you need to place all the class files and packages to you project root path.

This is the main logic to create the jar file programmatically:

private void createJar() throws IOException {
        String mainStr = txtMain.getText();
        String authorStr = txtAuthor.getText();
        String classesStr = txtAll.getText();
        if ((mainStr.length() < 1) || (classesStr.length() < 1)) {
            JOptionPane.showMessageDialog(null,
                    "Please complete 'Main Class' and 'Classes' fields");
        } else {
            boolean failed = false;
            File fileMft = new File("manifest.mf");
            FileWriter fwr = new FileWriter(fileMft);
            try {
                if ((fileMft.exists()) && (fileMft.isFile())) {
                    fileMft.delete();
                }
                fileMft.createNewFile();
                fwr.write("Manifest-Version: 1.0\n" + "Main-Class: " + mainStr + "\nCreated-By: " + authorStr + "\n");
                fwr.close();
            } catch (IOException x) {
                failed = true;
            }
            try {
                Runtime.getRuntime().exec("jar cmf manifest.mf " + mainStr + ".jar " + classesStr + " *.gif *.jpg");
            } catch (IOException x) {
                failed = true;
            }
            if (failed) {
                JOptionPane.showMessageDialog(null, "Jar creation failed for unknown reason(s)", "JarCreator", JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(null, "Jar creation successful: click on " + mainStr + ".jar to test the result", "JarCreator", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }

Screenshot:
jar_maker

 

admin

Hello! I am Md. Abdul Bari; founder and admin of javaknowledge; currently providing training as a J2EE faculty in The Computers Ltd. Dhaka, Bangladesh under an IT Scholarship project provided by IDB-BISEW. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

More Posts - Website

Follow Me:
TwitterFacebookGoogle Plus

5,544` Total Views

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *


1 + = two