views:

239

answers:

5

I've created a few .jar files (using Eclipse's export feature), but they were all GUIs. I want to create a .jar file that is strictly command-line; is this possible?

+2  A: 

Yes it's possible to create a console program in Java. Eclipse even has a Runnable JAR File Export.

I just created a dummy application that prints out the arguments given on the command line, then exported it as a jar and launched it using java -jar test.jar foo bar

package com.stackoverflow;

public class Test
{
  public static void main(String[] args)
  {
    for (int i = 0; i < args.length; ++i)
      System.out.println(args[i]);
  }
}

Then right click the Test.java file in Eclipse and use the "Export..." menu and select "Runnable JAR file" and export it for instance to C:\test.jar

Then open a command prompt and type java -jar C:\test.jar foo bar which prints out

foo
bar

Gregory Pakosz
+5  A: 

There is no such thing as a "GUI jar" or a "command line jar". If you want a program to work on the command line, then you read and write the from System.in and System.out or files rather than using Swing or AWT.

If on the other hand you are asking how to create a jar on the command line, the command is, not too surprisingly "jar". As in jar cf foo.jar com/my/foo/*.class

Paul Tomblin
+2  A: 

Yes, you can run your program with something similar to the following command-line

java -jar <JARFILE> <CLASSNAME>

You may have to specify -cp <DIRECTORY> or -classpath <DIRECTORY> to point it at any other jars you need.

MattGrommes
+1  A: 

I'm not sure what you're asking, but all depends on your code.

If your Java code uses JFrame and other GUI components then yes, when you create the jar you will have a GUI program.

If your Java code just prints on the screen without using any GUI components, then you'll have a console application.

Alex
+1  A: 

To automate things I would recommend using ant An ANT project looks like this

<project default="buildHello">
  <target name="compile">
    <javac srcdir="." />
  </target>

  <target name="jar" depends="compile">
    <jar destfile="hello.jar"
         basedir="."
         includes="**/*.class"
         />
  </target>

  <target name="buildHello" depends="compile,jar" />
</project>

It will be started by simply typing ant, eclipse also has support

> ant jar
Buildfile: build.xml

compile:

jar:
      [jar] Building jar: /Dev/hello.jar

BUILD SUCCESSFUL
Total time: 2 seconds
stacker