2017年11月3日 星期五

[ Java 常見問題 ] How do I make a JAR from a .java

Source From Here 
Question 
How to make a JAR from .java without help of IDE by javac and jar? Consider we have below files: 
  1. # tree ./  
  2. ./  
  3. ├── bin  
  4. ├── libs  
  5. │   └── commons-cli-1.4.jar  
  6. └── src  
  7.     └── Hello.java  
  8.   
  9. 3 directories, 2 files  
I want to compile Hello.java and archive it to jar "Hello.jar". 

How-To 
First at all, let's compile Hello.java: 
// -cp  Specify where to find user class files and annotation processors
// -d  Specify where to place generated class files

# javac -cp libs/commons-cli-1.4.jar -d bin/ src/*.java

Then it is time to archive *.class into Hello.jar
// -c create new archive
// -v generate verbose output on standard output
// -f specify archive file name
// -C change to the specified directory and include the following file

# jar -cvf Hello.jar -C bin/ .
added manifest
adding: Hello.class(in = 1580) (out= 839)(deflated 46%)

Finally, let's test the jar: 
# java -cp libs/commons-cli-1.4.jar:Hello.jar Hello -n 'John'
Hello John!

Supplement 
javac - Java programming language compiler 
jar - Manipulates Java Archive (JAR) files.

沒有留言:

張貼留言

[Linux 常見問題] How to set a file size limit for a directory?

Source From   Here   Question   I   have a directory on my system which is used for a specific reason by applications and users , but I   d...