Guide: Creating and Using a JAR File in Java (Windows CMD Friendly)
Step 1: Create Project Structure
---------------------------------
Use CMD (Command Prompt):
mkdir MyLibrary\src\com\example
mkdir MyLibrary\build
Step 2: Create Java Class
---------------------------
Use Notepad to create MathUtils.java:
notepad MyLibrary\src\com\example\MathUtils.java
Paste this code:
package com.example;
public class MathUtils {
public static int add(int a, int b) {
return a + b;
Save and close the file.
Step 3: Compile Java File
---------------------------
cd MyLibrary
javac -d build src\com\example\MathUtils.java
Step 4: Create JAR File
------------------------
cd build
jar cf MathUtils.jar com\example\MathUtils.class
Step 5: Set Up New Project to Use JAR
--------------------------------------
Create new folders:
mkdir ..\..\MyApp\src
mkdir ..\..\MyApp\lib
mkdir ..\..\MyApp\build
Copy the JAR file:
copy MathUtils.jar ..\..\MyApp\lib\
Step 6: Create Main.java
-------------------------
Use Notepad to create Main.java:
notepad ..\..\MyApp\src\Main.java
Paste this code:
import com.example.MathUtils;
public class Main {
public static void main(String[] args) {
int result = MathUtils.add(5, 7);
System.out.println("Result: " + result);
Save and close.
Step 7: Compile and Run
------------------------
cd ..\..\MyApp
Compile:
javac -cp lib\MathUtils.jar -d build src\Main.java
Run:
java -cp "build;lib\MathUtils.jar" Main
(Notice: On Windows, classpath separator is ';' not ':')
Summary of Differences on Windows:
------------------------------------
- mkdir path\to\folder (no -p option)
- notepad filename (instead of nano)
- classpath uses ';' not ':'
Done!