Saturday, September 13, 2014

Organize your code with package and jar (Notes of reading Head First Java)

I'm reading 'Head First Java' recently and here are some notes about package and jar.

Jar usage
  • Use jar file to compact your class files
    • /projects/class contains all classes files
    • /projects/source contains all java files
    • create manifest.txt under class
    • content of manifest.txt: 
    • Main-Class: <main_class> // don’t put .class on the end
    • Press the return key after typing the Main-Class line
  • Create jar file
    • cd /projects/class
    • jar -cvmf manifest.txt <file_name>.jar *.class
  • Execute jar file
    • java -jar <file_name>.jar
Organize your code in packages
  • Organize source code
    • /projects/source/com/shunrang/ contains all java files
    • Add this as the first line of all java files: package com.shunrang
  • Compile source code
    • mkdir /projects/class
    • cd /projects/souce
    • javac -d ../class com/shunrang/*.java
  • Run your code
    • cd /projects/class
    • java com.shunrang.<main_class>
    • The -d flag in javac will create the same structure under class folder as what is inside source folder
Combine Jar and package
  • Create manifest.txt file
    • Put manifest.txt under /projects/class
    • Content of manifest.txt: Main-Class: com.shunrang.<main_class>
  • Create Jar file
    • cd /projects/class
    • jar -cvmf manifest.txt <file_name>.jar com //All you specify is the com directory
  • Run Jar file
    • java -jar <file_name>.jar
  • Useful jar command
    • jar -tf <file_name>.jar //List the contents of a JAR, -tf stands for ‘Table File’
    • jar -xf <file_name>.jar //Extract the contents of a JAR, -xf stands for ‘Extract File'

No comments:

Post a Comment