สำหรับการแพ็คไฟล์คลาส Java จัดเตรียมรูปแบบไฟล์ที่เรียกว่า JAR (Java Archive) โดยทั่วไป ไฟล์ JAR จะมีไฟล์ .class, รูปภาพ, ไฟล์ข้อความ, ไลบรารี่ที่จำเป็นในการรันแอพพลิเคชั่นหรือ, ไลบรารี่
รูปแบบไฟล์นี้ใช้เพื่อแจกจ่ายซอฟต์แวร์แอปพลิเคชันและไลบรารีใน Java ไลบรารีที่กำหนดไว้ล่วงหน้าทั้งหมดมีอยู่ในรูปแบบนี้
หากคุณมีไลบรารีในรูปแบบนี้เพื่อใช้งาน ในแอปพลิเคชันของคุณ คุณจำเป็นต้องวางไว้ในโฟลเดอร์ปัจจุบัน (หรือ lib) ของโปรเจ็กต์ หรือ คุณต้องตั้งค่าคลาสพาธสำหรับไฟล์ JAR นั้น
การสร้างไฟล์ Jar
Java ให้คำสั่ง jar เพื่อทำงานกับไฟล์ jar หากคุณเรียกใช้งานใน command prompt คุณจะได้รับรูปแบบการดำเนินการและตัวเลือกของคำสั่งนี้ดังที่แสดงด้านล่าง -
C:\>jar
Usage: jar {ctxui}[vfmn0PMe] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
Options:
-c create new archive
-t list table of contents for archive
-x extract named (or all) files from archive
-u update existing archive
-v generate verbose output on standard output
-f specify archive file name
-m include manifest information from specified manifest file
-n perform Pack200 normalization after creating a new archive
-e specify application entry point for stand-alone application bundled into an executable jar file
-0 store only; use no ZIP compression
-P preserve leading '/' (absolute path) and ".." (parent directory) components from file names
-M do not create a manifest file for the entries
-i generate index information for the specified jar files
-C change to the specified directory and include the following file คุณสามารถสร้างไฟล์ JAR โดยใช้คำสั่งนี้โดยใช้ตัวเลือก c, v, f ต่อไปนี้เป็นรูปแบบคำสั่งเพื่อสร้างไฟล์ JAR โดยใช้ command prompt -
jar cvf jar_file_name output_path
ตัวอย่าง
สร้างไฟล์จาวาที่มีชื่อ Sample.java ในพาธ D:/example คัดลอกและวางโปรแกรมต่อไปนี้ในนั้น -
public class Sample {
public static void main(String args[]){
System.out.println("Hi welcome to Tutorialspoint");
}
} รวบรวมโปรแกรมข้างต้นโดยใช้คำสั่ง javac เป็น −
javac Example.java
หากโปรแกรมของคุณทำงานโดยไม่มีข้อผิดพลาด ไฟล์คลาสจะถูกสร้างขึ้นในโฟลเดอร์ปัจจุบัน ตอนนี้สร้างไฟล์ jar สำหรับคลาสที่สร้างเป็น -
C:\Sample>jar cvf sample.jar *.class added manifest adding: Sample.class(in = 434) (out= 302) (deflated 30%) Once you execute a JAR file is generated with the specified name.
การสร้างไฟล์ JAR โดยใช้ eclipse
คุณยังสามารถสร้างไฟล์ JAR โดยใช้ IDE ในการสร้างไฟล์ JAR โดยใช้ eclipse ให้ทำตามขั้นตอนด้านล่าง -
-
เปิด eclipse สร้างโปรเจ็กต์ใน −

-
คลิกขวาที่โฟลเดอร์โครงการและเลือก ส่งออก ตัวเลือกเป็น −

-
ภายใต้หมวดหมู่ Java ให้เลือกไฟล์ JAR

-
คลิกที่ ถัดไป .
-
ป้อนชื่อไฟล์ JAR และโฟลเดอร์
-
คลิกที่ เสร็จสิ้น .