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");

}



}

No comments:

Post a Comment