Category Archives: java

How to create and run a jar file

JAR (Java ARchive) is an archive file format typically used to aggregate many Java class files and associated metadata and resources (text, images and so on) into one file to distribute application software or libraries on the Java platform.

JAR files are built on the ZIP file format and have the .jar file extension. Computer users can create or extract JAR files using the jar command that comes with a JDK. They can also use zip tools to do so; however, the order of entries in the zip file headers is important when compressing, as the manifest often needs to be first.

How to create jar file
Into directory, there are at least java class files. It is important create the manifest file. Manifest file contains information about version, author, main class and other data about application created. Follow the TicTacToe example MANIFEST.MF file:
$ cat MANIFEST.MF
Manifest-Version: 1.0
Created-By: biliards
Main-Class: TicTacToe

Change directory where there are java class files and MANIFEST.MF file. To create jar file, edit this command line:
jar cfm TicTacToe.jar MANIFEST.MF TicTacToe*class

How to run jar file
The jar file created is runnable with follow command line:
java -jar TicTacToe.jar

JAR file manipulations
JAR file is a compress file and it is possible manipulate it in different ways:

  • view the contents of a JAR file
    jar tf TicTacToe.jar
  • extract the contents of a JAR file
    jar xf TicTacToe.jar
  • extract specific files from a JAR file
    jar xf TicTacToe.jar META-INF/MANIFEST.MF

Reference: Wikipedia, jar file and manifest file.

How to create and run a java file

Java files are source code edited by programmers from where to create executable files. An example about code structure is a sample TicTacToe game:

  1. create java file with main class (ie: TicTacToe class) and assign it the TicTacToe.java name
  2. if application is simple and uses few and simple classes, insert these class auxiliary into TicTacToe class
  3. else create one file for each class and declare each class into TicTacToe class

It is not possible run directly TicTacToe.java file. It needs to compile java file:
javac -g TicTacToe.java
and then it is possible run application recall name of main class:
java TicTacToe

This method is same if there are created one file for each class.

Reference: Wikipedia