开发者

Java Command Line Jar File

开发者 https://www.devze.com 2022-12-18 01:58 出处:网络
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?There is no such

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?


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


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


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.


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.


To automate things I would recommend using the Ant jar task. An Ant buildfile 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 Ant support.

> ant jar
Buildfile: build.xml

compile:

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

BUILD SUCCESSFUL
Total time: 2 seconds
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号