Poody
Poody

Reputation: 325

Creating jar from scratch with one class

After half a day of searching various stack threads and not finding an answer, I'll try to ask myself.

Method below is full of attempts to do the following. In a project, I have a class called A. This class is not used in the project, it has main() inside and small code to create a test file and display a javafx window. Method export creates a jar file with said class, marks it as a mainclass. I am looking for a way to slap a lib.jar into the output.jar file, whatever way is possible. I have to note that.. output.jar gets created, upon launching it doesn't show the javafx window, but creates the test file, so if you know the cause of that, feel free to contribute aswell. :)

public void export() {
    Manifest man = new Manifest();
    man.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    man.getMainAttributes().put(Attributes.Name.CLASS_PATH, ". mylib.jar");
    man.getMainAttributes().put(Attributes.Name.MAIN_CLASS, A.class.getName());
    try {
        JarOutputStream f = new JarOutputStream(new FileOutputStream("output.jar"), man);
        InputStream c = getClass().getResourceAsStream("A.class");
        JarEntry e = new JarEntry("A.class");
        f.putNextEntry(e); 
        byte[] buffer = new byte[1024];
        while (true) {
            int count = c.read(buffer);
            if (count == -1)
                break;
            f.write(buffer, 0, count);
        }
        f.closeEntry();  
        JarEntry cp = new JarEntry(".classpath");
        f.putNextEntry(cp); 
        String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                    + "<classpath>" 
                    + "<classpathentry kind=\"src\" path=\"src\"/>"
                    + "<classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/>"
                    + "<classpathentry kind=\"lib\" path=\"mylib.jar\"/>"
                    + "<classpathentry kind=\"output\" path=\"bin\"/>"
                    + "</classpath>";
        f.write(s.getBytes());
        f.closeEntry();
        f.close();
    } catch (IOException e) {}
}

Feel free to ask any further questions.

Upvotes: 0

Views: 123

Answers (1)

Pradhan
Pradhan

Reputation: 508

Assuming that your A class is under a package, change...
JarEntry e = new JarEntry("A.class");
to
JarEntry e = new JarEntry(SimpleJava.class.getName().replace('.', '/') + ".class");

This will put your A.class under the right package/directory structure in the jar.

XML parsers will have trouble reading the file if the file encodings does not match. So, to match the xml encoding mentioned in the .classpath file, update f.write(s.getBytes()); to f.write(s.getBytes("UTF-8"));

Hope this works for you.

Upvotes: 1

Related Questions