Thursday, October 31, 2013

Documentation in Java

In this tutorial, you will learn to do documentation of your Java programs. Java comes with a powerful tool called javadoc. This tool allows Java developer easily to create documentation of their programs. The javadoc tool extracts your comments embedded in the source code, constant fields, class name, methods and outputs these information in html files.
The comments that can be recognized by the javadoc tool must be placed between /** and */. Besides normal text, in the block of /** and */, there are some special tags that can be recognized by the javadoc tool. The table below summarizes these tags.

Tag Description Example
@author The author tag allows you to specify the information about the author. @author Dara Yuk
@deprecated This tag specifies that a class or method is deprecated in the current version. @deprecated Deprecated
@exception This tag is used to specify the type of exception to be thrown. @exception IOException
{@link} This tag is used to specify the in-line link to other page. See the {@link <a href="JCalc.htm">JCalc</a>}
@param This tag specifies the parameter of a method. @param a
@return This tag allows you to specify the return value of a method. @return sum
@see You can use this tag to provide a link to other topic or page. This link will shown at the "See Also" section of the page. @see <a href="Jtutorial.html">Java Tutorial</a>
@serial This tag specifies the default serial field. You can describe the field and its possible values. The information about this tag will be shown in the Serial Form page. @serial The PI field
@since You will use this tag to spcify the version of your software when a specific change was introduced. @since 1.6
{@value} You will use this tag to display the value of a constant field. The value of this field is {@value}.
@version This tag will be used to specify the current version of your software. @version 1.0

For example, you have the JCalc class that is a simple calculator class. It contains twelve methods that can be used to add, subtract, multiply, and divide integer and floating-pointer numbers.

/**
 * This is the JCalc class. It has twelve methods that can be called to add, subtract, multiply,
 * and divide floating-point numbers. See the {@link <a href="index.html">JCalc</a>}.
 * @author Dara Yuk 
 * @version 1.0
 * 
 */
public class JCalc{

/**
* The value of the constant is {@value}.
*/
public static final double PI=Math.PI;
public static void main(String[] args){

}
/**
* This method adds two integer values a and b.
* @param a
* @param b
* @return a+b
* @see <a href="JavaTutorial.html">Java Tutorial</a>
*/
public int sum(int a,int b){
return(a+b);
}
/**
* This method adds two float values a and b.
* @param a
* @param b
* @return a+b
*/
public float sum(float a,float b){
return(a+b);
}
/**
* This method adds double values a and b.
* @param a
* @param b
* @return a+b
*/
public double sum(double a,double b){
return(a+b);
}

/**
* This method subtracts b from a. The parameters a and b are integer. 
* @param a
* @param b
* @return a-b
*/
public int subtract(int a,int b){
return(a-b);
}
/**
* This method subtracts b from a. The parameters a and b are float. 
* @param a
* @param b
* @return a-b
*/
public float subtract(float a,float b){
return(a-b);
}
/**
* This method subtracts b from a. The parameters a and b are double. 
* @param a
* @param b
* @return a-b
*/
public double subtract(double a,double b){
return(a-b);
}

/**
* This method multiplies a and b. The parameters a and b are integer.
* @param a
* @param b
* @return a*b
*/
public int multiply(int a,int b){
return(a*b);
}
/**
* This method multiplies a and b. The parameters a and b are float.
* @param a
* @param b
* @return a*b
*/
public float multiply(float a,float b){
return(a*b);
}
/**
* This method multiplies a and b. The parameters a and b are double.
* @param a
* @param b
* @return a*b
*/
public double multiply(double a,double b){
return(a*b);
}
/**
* This method divides a by b. The parameters a and b are integer.
* @param a
* @param b
* @return a/b
*/
public double divide(int a,int b){
return(a/b);
}
/**
* This method divides a by b. The parameters a and b are float.
* @param a
* @param b
* @return a/b
*/
public float divide(float a,float b){
return(a/b);
}
/**
* This method divides a by b. The parameters a and b are double.
* @param a
* @param b
* @return a/b
*/
public double divide(double a,double b){
return(a/b);
}
}


To create the document of the JCalc class, from the command prompt, enter the directory that contains the JCalc.java file and type the following command:


D:\eclipse\charts\Calculator\src>javadoc -d docs JCalc.java

While javadoc is processing the file, the messages below are displayed on the screen.

Loading source file JCalc.java...
Constructing Javadoc information...
Standard Doclet version 1.7.0_21
Building tree for all the packages and classes...
Generating docs\JCalc.html...
Generating docs\package-frame.html...
Generating docs\package-summary.html...
Generating docs\package-tree.html...
Generating docs\constant-values.html...
Generating docs\serialized-form.html...
Building index for all the packages and classes...
Generating docs\overview-tree.html...
Generating docs\index-all.html...
Generating docs\deprecated-list.html...
Building index for all classes...
Generating docs\allclasses-frame.html...
Generating docs\allclasses-noframe.html...
Generating docs\index.html...
Generating docs\help-doc.html...

The document pages will be generated in the src/docs folder.


Tuesday, October 29, 2013

E-mail in Java

This is a simple E-mail in Java program. You can use it to send message with multiple attachments to multiple recipients at the same time. Before you use the program to send e-mail message, you will need to configure the mail. The configuration form allows you to enter the outgoing server name, port, user name and password to log in the server. For security reason, your password is encrypted. The configuration file (mailconfigs.con) is stored in your current working folder. You can configure the email by going to File menu->Setup Configuration...One you configured the mail correctly, you do not need to configure it again later.

configure e-mail


After you configured the mail, you will need to input the From address (your e-mail address), the recipients' e-mail addresses, subject, and message of the mail. Bcc, Cc e-mail addresses, and file attachments are optional.



In Java, it is easy to send e-mail by using the Apache Commons Mail api. You will download the Apache Commons Mail api from its website. This api depends on the Java Mail api. You can download Java Mail api from here. After downloading the two api, extract the zip files and add the jar files (commons-email-1.3.2.jar and javax.mail.jar) to the Java Build Path in the Eclipse.

In the Commons Mail api, there two classes that can be used to send e-mail message. One class is SimpleEmail. The SimpleEmail class is used to send e-mail message without attachment. Another class is called MultiPartEmail. This class is able to send e-mail message with attachments. Like the SimpleEmail class, the MultiPartEmail class has methods that allow you to configure e-mail in your Java code.

MultiPartEmail email=new MultiPartEmail();
//set the outgoing mail server
email.setHostName(smtp);
//set the server port
email.setSmtpPort(port);
//provide user name and password
email.setAuthentication(user,password);
//set SSL encryption for mail transfer
email.setSSLOnConnect(true);

There are other methods that you will use to set the From e-mail address, To e-mail addresses, Bcc e-mail adddress, Cc e-mail addresses, subject, message, and attachment of the mail.

//add sender's e-mail address
email.setFrom(from);
//add subject
email.setSubject(subject);
//add message
email.setMsg(message);
//specify recipient's (to) e-mail address
email.addTo(Toadd);
//add recipient's (Bcc) e-mail address
email.addBcc(Bccadd);
//add recipient's (Cc) e-mail address
email.addCc(Ccadd);
//add file attachment
email.attach(new File(path));

//send the email
email.send();

Here is the complete code of the E-mail in Java program.

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;


class UI extends JFrame implements ActionListener{
JTextField textfrom;
JTextField textto;
JTextField textbcc;
JTextField textcc;
JTextField textsubject;
JTextArea textmessage;
JLabel lblstatus;
JTextField txtserver;
JTextField txtport;
JTextField txtuser;
JPasswordField txtpwd;
DefaultListModel<String> listmodel;
MultiPartEmail email;
ArrayList<String> configs;
JFrame frame;
UI(String title){

Container cont=getContentPane();
setTitle(title);
setResizable(false);
setSize(new Dimension(650,500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar mbar=new JMenuBar();
JMenu mfile=new JMenu("File");
mfile.setMnemonic('F');
JMenuItem itemserver=new JMenuItem("Mail configure...");
itemserver.addActionListener(this);
JMenuItem itemexit=new JMenuItem("Exit");
itemexit.addActionListener(this);
mfile.add(itemserver);
mfile.add(itemexit);
mbar.add(mfile);
setJMenuBar(mbar);

JPanel panelmain=new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel lblfrom=new JLabel("From:");
textfrom=new JTextField(30);
JButton btadd=new JButton("Send");
btadd.addActionListener(this);
JPanel panelnorth=new JPanel();
panelnorth.add(lblfrom);
panelnorth.add(textfrom);
panelnorth.add(btadd);
GridBagLayout gbl=new GridBagLayout();
JPanel panelcenter=new JPanel(gbl);
GridBagConstraints gc = new GridBagConstraints();
JLabel lblto=new JLabel("To:");
textto=new JTextField(30);
JLabel lblbcc=new JLabel("Bcc:");
textbcc=new JTextField(30);
JLabel lblcc=new JLabel("Cc:");
textcc=new JTextField(30);
JLabel lblsubject=new JLabel("Subject:");
textsubject=new JTextField();
JButton btatt=new JButton("Attach");
btatt.addActionListener(this);

listmodel=new DefaultListModel<String>();
JList<String> attlist=new JList<String>(listmodel);
attlist.setVisibleRowCount(5);

gc.fill = GridBagConstraints.BOTH;
       gc.weightx = 1.0;
       gbl.setConstraints(lblto, gc);
       gc.gridwidth = GridBagConstraints.REMAINDER;
       gbl.setConstraints(textto, gc);
      panelcenter.add(lblto);
panelcenter.add(textto);

gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblbcc, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(textbcc, gc);
      panelcenter.add(lblbcc);
panelcenter.add(textbcc);

gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblcc, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
   gbl.setConstraints(textcc, gc);
      panelcenter.add(lblcc);
panelcenter.add(textcc);


gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(lblsubject, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
       gbl.setConstraints(textsubject, gc);
      panelcenter.add(lblsubject);
panelcenter.add(textsubject);

gc.gridwidth = GridBagConstraints.RELATIVE;
gbl.setConstraints(btatt, gc);
gc.gridwidth = GridBagConstraints.REMAINDER;
gc.gridheight = 2;
       gbl.setConstraints(attlist, gc);
      panelcenter.add(btatt);
panelcenter.add(attlist);

gc.gridwidth = GridBagConstraints.RELATIVE;
gc.weighty = 1.0;
lblstatus=new JLabel("");
lblstatus.setForeground(Color.RED);
gbl.setConstraints(lblstatus, gc);
panelcenter.add(lblstatus);


JPanel panelsouth=new JPanel(new FlowLayout(FlowLayout.LEFT));
panelsouth.add(new JLabel("Message:"));
textmessage=new JTextArea(15,50);
textmessage.setWrapStyleWord(true);
JScrollPane scroll=new JScrollPane(textmessage);
panelsouth.add(scroll);

panelmain.add(panelnorth);
panelmain.add(panelcenter);
panelmain.add(panelsouth);
cont.add(panelmain);
setVisible(true);
configureMail();
}
public void configureMail(){
readConfigs();
if(configs.size()>2){
setEmailConfigs(configs.get(0),Integer.parseInt(configs.get(1)),configs.get(2),configs.get(3));

}
}

public void actionPerformed(ActionEvent e){
String[] Tos=null;
String[] Bccs=null;
String[] Ccs=null;
if(e.getActionCommand().equals("Send")){
String from=textfrom.getText();
if(textto.getText().length()>0)
Tos=textto.getText().split(", ");
if(textbcc.getText().length()>0)
Bccs=textbcc.getText().split(", ");
if(textcc.getText().length()>0)
Ccs=textcc.getText().split(", ");
String subject=textsubject.getText();
String message=textmessage.getText();

if(from.length()>0 && Tos.length>0 && subject.length()>0 && message.length()>0) {
Th th=new Th(from,Tos,Bccs,Ccs,subject,message);
th.start();

}
else{
JOptionPane.showMessageDialog(this,"From, To, Subject, and Message cannot be blank.");
textfrom.requestFocus();
}

}
else if(e.getActionCommand().equals("Attach")){
selectFile();
}
else if(e.getActionCommand().equals("Exit")){
System.exit(0);
}
else if(e.getActionCommand().equals("Mail configure...")){
JPanel p=new JPanel(new GridLayout(5,1));
txtserver=new JTextField("Enter outgoing server");
txtport=new JTextField("Enter server port");
txtuser=new JTextField("Enter user name");
txtpwd=new JPasswordField("Enter password");
JButton bt=new JButton("Save and Close");
bt.addActionListener(this);
p.add(txtserver);
p.add(txtport);
p.add(txtuser);
p.add(txtpwd);
p.add(bt);

frame=new JFrame("Configure mail");
frame.getContentPane().add(p);
frame.setSize(300, 200);
frame.setVisible(true);

}
else if(e.getActionCommand().equals("Save and Close")){
saveConfigs();
frame.dispose();
}
}
class Th extends Thread{
String from;
String[] Tos=null;
String[] Bccs=null;
String[] Ccs=null;
String subject;
String message;
Th(String fromaddr,String[] toaddr,String[] bccaddr,String[] ccaddr,String subj,String mess){
from=fromaddr;
Tos=toaddr;
Bccs=bccaddr;
Ccs=ccaddr;
subject=subj;
message=mess;
lblstatus.setText("Sending the message");

}
public void run(){
sendEmail(from,Tos, Bccs,Ccs,subject, message);
email=null; //create object
lblstatus.setText("");
}
}
public void readConfigs(){
configs=new ArrayList<String>();
BufferedReader br=null;
try {
File f=new File("mailconfigs.con");
if(f.exists()){
FileReader fr=new FileReader(f);
br=new BufferedReader(fr);
String line="";
while((line=br.readLine())!=null){
configs.add(line);
}
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null)
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

public void saveConfigs(){
FileWriter fw=null;
BufferedWriter bw=null;
try {
fw = new FileWriter("mailconfigs.con");
bw=new BufferedWriter(fw);
bw.write(txtserver.getText());
bw.newLine();
bw.write(txtport.getText());
bw.newLine();
bw.write(txtuser.getText());
bw.newLine();
bw.write(encrypt(new String(txtpwd.getPassword())));



} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(bw!=null)
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}



public String encrypt(String passw){
byte[] sb=passw.getBytes();
int i;
for(i=0;i<sb.length;i++)
sb[i]=(byte)(sb[i]+101);

return(new String(sb));
}

public String decrypt(String passw){

byte[] sb=passw.getBytes();
int i;
for(i=0;i<sb.length;i++)
sb[i]=(byte)(sb[i]-101);

return(new String(sb));
}

public void selectFile(){
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(false);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File file=chooser.getSelectedFile();
listmodel.addElement(file.getPath());
       }
}

public void setEmailConfigs(String smtp,int port, String user, String password){
email = new  MultiPartEmail();
//set the outgoing mail server
email.setHostName(smtp);
//set the server port
email.setSmtpPort(port);
//provide user name and password
email.setAuthentication(user,decrypt(password));
//set SSL encryption for mail transfer
email.setSSLOnConnect(true);
}

public void sendEmail(String from, String[] Tos, String[] Bccs, String[] Ccs, String subject, String message){
configureMail();

if(email.getHostName().length()>0){
try {
//add sender's e-mail address
email.setFrom(from);
//add subject
email.setSubject(subject);
//add message
email.setMsg(message);
//specify recipients' (to) e-mail addresses
if(Tos!=null)
for(String Toadd:Tos)
email.addTo(Toadd);
//add recipients' (Bcc) e-mail addresses
if(Bccs!=null)
for(String Bccadd:Bccs)
email.addBcc(Bccadd);
//add recipients' (Cc) e-mail addresses
if(Ccs!=null)
for(String Ccadd:Ccs)
email.addCc(Ccadd);
//add file attachments
for(int i=0;i<listmodel.getSize();i++)
email.attach(new File(listmodel.get(i)));

//send the email
email.send();
}catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
JOptionPane.showMessageDialog(this,"The email is not configured.");
}

}
}
public class EmailSender {
public static void main(String[] args){
new UI("E-Mail Sender");
}
}


Saturday, October 26, 2013

Charts in Java

In Java, if you know Graphics or Graphics2D class, you can write your own code to create a simple chart to present data. However, if you do not want to spend one or two hours to write code to construct the simple bar chart or pie chart, using a third-part library is your best alternative. The free popular third library to construct different types of charts i recommend is JFreeChart. You can download the JFreeChart library and its dependency JCommons from here. There are many types of charts such as Bar chart, Pie chart, line chart, Gant chart, Polar chart, Ring chart and more that are supported by the JFreeChart tool. A chart created by the JFreeChart library can be saved in PNG image format, printed, or exported to PDF document.

For the examples in this tutorial, we are going to create two charts, one Bar chart and one Pie chart. Before continuing to the rest of the tutorial, you will need to add the JFreeChart library (jfreechart-1.0.16.jar) and JCommons library (jcommon-1.0.21.jar) to the Java Build Path of Eclipse (Project->Properties->Java Build Path->Libraries->Add External Jars...).

When you create a Bar chart or Pie chart, there are three steps that should be undertaken. The first step is creating the dataset for the chart. The second step creates the chart object that wraps the dataset and the last step shows the chart on the frame window. For the Bar chart, you can construct the dataset by using the DefaultCategoryDataset. This class has a method called setValue that can be used to set the values, row keys, and column keys to the chart.

DefaultCategoryDataset dataset=new DefaultCategoryDataset();

To create a Bar chart, you will use the createBarChart or createBarChart3D method of the ChartFactory class. The createBarChart method allows you to create a simple Bar chart with 2D effect. If you want the Bar chart with 3D effect, you will use the createBarChart3D method. With these methods, you can specify the chart title, category label, value label, and dataset.

JFreeChart barchart=ChartFactory.createBarChart("People used Facebook in Cambodia", "Year", "Number", dataset);


After the chart object is created, it is ready to show on the frame window. It is easy. The ChartFrame class allows you to create a frame window. You need to provide the frame title, and the chart object that you created in the second step. Then call the pack and setVisible methods to show the window.

JFrame frame = new ChartFrame("Bar chart", barchart);

Here is the complete program to construct a Bar chart with.


import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;


public class PieChart {
public static void main(String[] args) {
createBarChart();

}

public static void createBarChart(){
        //create dataset for Bar chart
DefaultCategoryDataset dataset=new DefaultCategoryDataset();
dataset.setValue(new Integer(1000),"Men","2000");
dataset.setValue(new Integer(3000),"Women","2000");
dataset.setValue(new Integer(7000),"Men","2001");
dataset.setValue(new Integer(15000),"Women","2001");
        //create Bar chart
JFreeChart barchart=ChartFactory.createBarChart("People used Facebook in Cambodia", "Year", "Number", dataset);
        //show the chart
JFrame frame = new ChartFrame("Bar chart", barchart);
frame.pack();
frame.setVisible(true);

            }



}


create bar chart with JFreeChart



For a Pie chart, you will use the DefaultPieDataset to create the dataset object for the Pie chart. This class also has the setValue method that you can set the value for each category of the chart. The createPieChart method of the ChartFactory class allows you to create a Pie chart with 2D effect. If you like 3D effect, you can use the createPieChart3D instead.

public static void createPieChart(){

// create a dataset for pie chart
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Men", new Integer(1200));
dataset.setValue("Women", new Integer(500));
dataset.setValue("Children", new Integer(1000));
// create a pie chart by using ChartFactory
JFreeChart piechart = ChartFactory.createPieChart3D("Pie chart", dataset,true,true,false);

// create and display a frame...
JFrame frame = new ChartFrame("Test", piechart);
frame.pack();
frame.setVisible(true);


}

create pie chart with JFreeChart



The JFreeChart library allows you to save the chart objects in PNG image format, print them to the default printer, set chart properties (title, font, color, ...) or copy the chart to other applications easily without writing a single line of code. You just right-click on the chart then select a task from the popup menu.

copy, print, and save chart with JFreeChart


If you want to save the chart in PDF file format, you will do more code. Don't worrry. It is not hard. The JFreeChart class allows you create BufferedImage object from the chart object by using its createBufferedImage method. When you get the BufferedImage object, you can convert it to an image object and write this image object to the PDF output file by using the iText library. You need add the iText library to the Java Build Path as you did with the JFreeChart library.

public static void saveToPDF(JFreeChart chart){
Document doc=new Document();
try {
PdfWriter.getInstance(doc,new FileOutputStream("d:/chart.pdf"));
doc.open();
//store the image data in memory
ByteArrayOutputStream bas=new ByteArrayOutputStream();
ImageIO.write(chart.createBufferedImage(500, 400), "png", bas);
//create image from the image data stored in memory
Image img=Image.getInstance(bas.toByteArray());
//add the chart image on the pdf page
doc.add(img);


} catch (Exception e) {
e.printStackTrace();
} finally{
if(doc!=null)
doc.close();
}


}

save chart in pdf file with iText

Thursday, October 24, 2013

Jar Pack

This is a simple Jar Pack program. You can use it to compress files or directories from your computers in a single jar file. It can be also used to extract an existing jar or zip file. The Jar Pack program has a very simple user interface which is divided in to two sections or parts. In the first section, there is a text box that you can enter the file or directory path to compress. Alternatively, you can click the Browse button to select a file from your computer. The file chooser allows you to select only file item. The selected file path will display in the text box. If you want to compress the directory that contains the file, you simply need to remove only the file name from the text box. You will press OK button to start compress the file or directory. The second section is similar to the first section except that it is for opening or extracting an existing jar or zip file.

The Jar Pack program uses the Apache Tika library to detect the mine type of file that the user selected to extract or open. Since this program is able to extract jar or zip file format, only a jar file or a zip file is allowed to extract. You will need to add the Tika library to the Java Build Path in Eclipse (Project->Properties->Java Build Path->Libraries->Add External Jars...) before you run the program.



In Java, creating jar and zip files are almost the same. The difference is that to create a jar file, you need to use the JarOutputStream class to write the content of the jar output file. Creating a zip file requires you to use the ZipOutputStream to write the content of the zip output file. Please read the Create Zip file page to read code explanation on compressing files and directories in zip file. Opening or extracting the jar file and the zip file are the sample so that you can read the code explanation about extracting a zip file on page Extract Zip.

Jar Pack program's source code

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.apache.tika.Tika;

class JarUI extends JFrame{
JTextField txtFilePath;
JButton btFileBrowse;
JButton btFileOK;
JLabel lblFile;
JTextField txtArchivePath;
JButton btArchiveBrowse;
JButton btArchiveOK;
JLabel lblArchive;

JarUI(String title){
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,300);
setResizable(false);
Container cont=getContentPane();
cont.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel pPanel=new JPanel();
pPanel.setLayout(new BoxLayout(pPanel,BoxLayout.Y_AXIS));
JPanel filePanel=new JPanel(new GridLayout(2,2));
filePanel.setBorder(BorderFactory.createTitledBorder("Add to archive"));
txtFilePath=new JTextField(30);
btFileBrowse=new JButton(new AAction("Browse"));
btFileOK=new JButton(new AAction("OK"));
lblFile=new JLabel();
filePanel.add(txtFilePath);
filePanel.add(btFileBrowse);
filePanel.add(btFileOK);
filePanel.add(lblFile);

JPanel archivePanel=new JPanel(new GridLayout(2,2));
archivePanel.setBorder(BorderFactory.createTitledBorder("Extract jar or zip file"));
txtArchivePath=new JTextField(30);
btArchiveBrowse=new JButton(new AAction("Browse"));
btArchiveOK=new JButton(new AAction("OK"));
lblArchive=new JLabel();
archivePanel.add(txtArchivePath);
archivePanel.add(btArchiveBrowse);
archivePanel.add(btArchiveOK);
archivePanel.add(lblArchive);
pPanel.add(filePanel);
pPanel.add(archivePanel);
cont.add(pPanel);

setVisible(true);
}

class AAction extends AbstractAction{

AAction(String text){
super(text);
}
public void actionPerformed(ActionEvent e){

JButton bt=(JButton)e.getSource();
if(bt==btFileBrowse)
{
selectFile(txtFilePath);
}
else if(bt==btArchiveBrowse){
selectFile(txtArchivePath);
}
else if(bt==btFileOK){
final String path=txtFilePath.getText();
if(path.length()>0){
lblFile.setText("Please wait");
Thread t=new Thread(){
public void run(){
createJar(path);
lblFile.setText("Complete");
}
};
t.start();

}
else{
JOptionPane.showMessageDialog(null,"There is no file or folder name.");
}
}
else {
final String path=txtArchivePath.getText();
if(path.length()>0){
boolean b=isJarOrZip(path);
if(b){
lblArchive.setText("Please wait");
if(path.length()>0){
Thread t=new Thread(){
public void run(){
extractFile(txtArchivePath.getText(), System.getProperty("user.dir"));
lblArchive.setText("Complete");
}
};
t.start();

}
}
else{
JOptionPane.showMessageDialog(null,"It is not a jar or zip file.");
}
}
else{
JOptionPane.showMessageDialog(null,"There is no file name.");
}
}
}
}

//allow office word file selection for extracting
public void selectFile(JTextField path){

JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
    int returnVal = chooser.showOpenDialog(null);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
    File file=chooser.getSelectedFile();    
    path.setText(file.getPath());
    }

     
}

public boolean isJarOrZip(String file){
boolean isJOZ=false;
Tika tika=new Tika();
try {
String mineType=tika.detect(new File(file));
if(mineType.endsWith("java-archive") || mineType.endsWith("zip"))
isJOZ=true;

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isJOZ;
}

public static void extractFile(String srcfile, String despath){
ZipFile zf=null;
    try {
zf=new ZipFile(srcfile); //create  a zip file object
if(zf.size()>0){ //read through the zip file
Enumeration<ZipEntry> entries=(Enumeration<ZipEntry>) zf.entries();
while(entries.hasMoreElements()){
ZipEntry entry=entries.nextElement();
if(!entry.isDirectory() && !entry.getName().endsWith("/")){
//start extracting the files
extract(zf.getInputStream(entry),entry.getName(),despath);

}

}

}


} catch (IOException e) {

e.printStackTrace();

}finally{
if(zf!=null)
try {
zf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
    }
public static void extract(InputStream is, String fname, String storeDir){

FileOutputStream fos;
File fi=new File(storeDir+File.separator+fname); //output file
File fparent=new File(fi.getParent());
fparent.mkdirs();//create parent directories for output files

try {

fos=new FileOutputStream(fi);
int content=0;
while((content=is.read())!=-1){
fos.write(content);
}
is.close();
fos.close();
} catch (Exception e) {

e.printStackTrace();
}

}

//packaging file or directory
public void createJar(String src){
File f=new File(src);
File foutdir=new File(System.getProperty("user.dir")+"/jars");
if(!foutdir.exists()) foutdir.mkdir();
JarOutputStream zos=null;
try{
zos=new JarOutputStream(new FileOutputStream(foutdir.getPath()+"/jar"+System.currentTimeMillis()+".jar"));
if(f.exists()){
String fname=getName(f.getPath());
if(f.isFile()){
packFile(f.getPath(),fname,zos);
}
else{ //source is a directory
File[] files=f.listFiles();
for(File sf:files){
packDir(sf.getPath(),fname,zos);
}
}


}
else{
System.out.println("Soure not found!");
}
zos.close();

}catch(Exception e){e.printStackTrace();}

}
//get the name of source file or directory
public String getName(String srcpath){

String name="";
if(srcpath.endsWith(File.separator)){
name=srcpath.substring(0,srcpath.length()-1);
name=name.substring(name.lastIndexOf(File.separator)+1);
}
else
name=srcpath.substring(srcpath.lastIndexOf(File.separator)+1);

return name;
}
//packaging the directory and its contents
public void packDir(String srcpath, String dirname, JarOutputStream zos){
File fsrcdir=new File(srcpath);
String curDirName=getName(srcpath);
if(fsrcdir.isDirectory()){
try {
//add the blank folder to the jar file
//its previous path is maintained
curDirName=dirname+File.separator+curDirName;
zos.putNextEntry(new ZipEntry(curDirName+File.separator));
zos.closeEntry();
//read the contents of the directory and place them in the jar file
File[] files=fsrcdir.listFiles();
for(File f:files){
if(f.isDirectory()){ //process one directory download
packDir(f.getPath(),curDirName,zos);
}
else{//process the file
packFile(f.getPath(),curDirName,zos);
}
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
packFile(srcpath,dirname,zos);
}
}
//packaging  the file
public void packFile(String srcfile, String dirname,JarOutputStream zos){

String rpath=getName(srcfile);
//The rpath is a directory name that the file will be stored in
//It is the immediate parent directory of the file
try {
//placing one file entry
zos.putNextEntry(new ZipEntry(dirname+File.separator+rpath));
//create FileInputStream object to read content of the file
FileInputStream fis=new FileInputStream(srcfile);
int content=0;
while((content=fis.read())!=-1){
zos.write(content);
}
zos.closeEntry(); //closing one file entry
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}



}
public class JarCreator {

public static void main(String[] args) throws IOException{
new JarUI("Jar Pack");

}



}