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 [Link]:
notepad MyLibrary\src\com\example\[Link]
Paste this code:
package [Link];
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\[Link]
Step 4: Create JAR File
------------------------
cd build
jar cf [Link] com\example\[Link]
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 [Link] ..\..\MyApp\lib\
Step 6: Create [Link]
-------------------------
Use Notepad to create [Link]:
notepad ..\..\MyApp\src\[Link]
Paste this code:
import [Link];
public class Main {
public static void main(String[] args) {
int result = [Link](5, 7);
[Link]("Result: " + result);
Save and close.
Step 7: Compile and Run
------------------------
cd ..\..\MyApp
Compile:
javac -cp lib\[Link] -d build src\[Link]
Run:
java -cp "build;lib\[Link]" 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!