user2826304
user2826304

Reputation: 117

Building a jar file from .java files in java

Hello members of StackOverflow.

I am wanting to build a jar file in my java application with the following code:

    private void javaToClass()
{
    try {
        String path = new File(".").getCanonicalPath();
        String command = "cmd /c javac " + path + "\\files\\*.java";

        System.out.println("Building class files...");
        Runtime.getRuntime().exec(command);
        System.out.println("Class files have been built");
    } catch (IOException e) {
    }
}

private void classToJar()
{
    try {
        String path = new File(".").getCanonicalPath();
        String command = "cmd /c jar cf Built.jar " + path + "\\files\\*.class";

        System.out.println("Building jar file...");
        Runtime.getRuntime().exec(command);
        System.out.println("Jar file has been built");
    } catch (IOException e) {

    }
}

So this builds the jar file but it doesn't add the class files to the jar file. Instead it will add my systems directory: https://i.sstatic.net/cTrbO.png

So if anybody could explain to me how i would make it only add my class files it would be a great help.

Thanks.

Upvotes: 0

Views: 231

Answers (2)

Whome
Whome

Reputation: 10400

Should jar command use -C parameter? Here is my jar syntax, where I give an explicit manifest file as well. You can leave that out and remove m option from options list.

jar cvfm ./lib/MyLib.jar ./classes/META-INF/MANIFEST.MF -C ./classes .

Another tip is you can use unix / path delimiter even in Windows for java commands and java fileio manipulations. Its a nice way keeping program Unix and Windows compatible.

Doublecheck working directory of shellexec process, you can give an explicit working dir(current dir). Or give an absolute filepaths to all file arguments (jarname, classes folder)
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec%28java.lang.String[],%20java.lang.String[],%20java.io.File%29

Upvotes: 1

Navin
Navin

Reputation: 21

You can do this using java.util.jar package.

http://docs.oracle.com/javase/6/docs/api/java/util/jar/package-summary.html

Upvotes: 0

Related Questions