Saturday, January 24, 2009

Java : Simple Program to Create zip file.

It can be used to zip both a file or a Directory. Directory is ziped along with its subdirectory structure. Just Provide the proper source and run the code.


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CreateZip {
   
    //function to zip a single file
    //Parameters List :
    //zipSrc : source file which to be ziped
    //zipName : Give desire name to zip file
    //destination folder where to create zip file
    public void zipFile(File zipSrc,String zipName,String destFolder) {
       
        System.out.println("zipFile :: "+zipSrc.getPath()+" "+zipName+" "+destFolder);
       
        try {           
                   
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destFolder+File.separator+zipName));
                   
            FileInputStream fis = new FileInputStream(zipSrc);
           
            ZipEntry zipEntry = new ZipEntry(zipSrc.getName());
           
            zos.putNextEntry(zipEntry);
           
            int bytes = 0;
            byte[] buffer = new byte[2156];
           
            bytes = fis.read(buffer);
           
            while (bytes != -1) {
                zos.write(buffer, 0, bytes);
                bytes = fis.read(buffer);
            }
           
            fis.close();
            zos.flush();
            zos.close();
           
        } catch (Exception e) {
           
            System.out.println("Exception :: "+e);
           
        }
    }
   
    //function to zip a folder containing multiple files
    //Parameters List :
    //zipSrc : source folder which to be ziped
    //zipName : Give desire name to zip file
    //destination folder where to create zip file
    public void zipDirectory(File zipSrc,String zipName,String destFolder) {
       
        System.out.println("zipDirectory :: "+zipSrc.getPath()+" "+zipName+" "+destFolder);
       
        try {
           
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destFolder+File.separator+zipName));
           
            zipDirectoryUtil(zipSrc.getPath(),zos,"");
            zos.close();       
        }
        catch (Exception e) {
           
            e.printStackTrace();
        }
       
    }
   
    public void zipDirectoryUtil(String directory,ZipOutputStream zos,String path) {
       
        try {
           
            File zipDir = new File(directory);
           
            String[] allFiles = zipDir.list();
           
            int bytes = 0;
            byte[] buffer = new byte[2156];
           
            for (String eachFile : allFiles) {
               
                File file = new File(zipDir,eachFile);
               
                if(file.isDirectory()) {
                   
                    zipDirectoryUtil(file.getPath(),zos,path+file.getName()+File.separator);
                    continue;
                }
               
            FileInputStream fis = new FileInputStream(file);
           
            ZipEntry zipEntry = new ZipEntry(path+file.getName());
           
            zos.putNextEntry(zipEntry);
           
            bytes = fis.read(buffer);
           
            while (bytes != -1) {
                zos.write(buffer, 0, bytes);
                bytes = fis.read(buffer);
            }
            fis.close();
           
            }
        }
        catch (Exception e) {
           
            e.printStackTrace();
        }
    }
   
    public static void main(String[] args) {
       
        CreateZip obj = new CreateZip();
       
        obj.zipFile(new File("C:\\MY\\Code\\Photo.jpg"),"img.zip","D:\\Test\\data");
       
        obj.zipDirectory(new File("C:\\MY\\Code\\com"),"com.zip","D:\\Test\\data");

    }

}

Java : Simple Program for Unzipping a File

Just provide a zip file which to be unziped and run the code.


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class Unziping {
  
    //Function to unzip a file, provide source zip file and destination directory where to unzip a file
    public void unzip(File zipFile,String destFolder) {
      
        System.out.println("Unzip :: "+zipFile.getPath()+" into "+destFolder);
      
        try {
            ZipFile zip = new ZipFile(zipFile);
          
            File dest = new File(destFolder);
          
            Enumeration files = zip.entries();
          
            File file;
            FileOutputStream fos;
          
            int bytes = 0;
            byte[] buffer = new byte[2156];
          
            while (files.hasMoreElements()) {
              
                ZipEntry entry = (ZipEntry)files.nextElement();
              
                InputStream eis = zip.getInputStream(entry);
                file = new File(dest.getAbsolutePath() + File.separator + entry.getName());
              
                if (entry.isDirectory()) {
                    file.mkdirs();
                    continue;
                }
                else {
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                }
              
                fos = new FileOutputStream(file);
              
                while ((bytes = eis.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytes);
                  }
              
                fos.close();              
            }          
          
        } catch (Exception e) {
          
            e.printStackTrace();
        }
    }
  
    public static void main(String[] args) {
      
        Unziping obj = new Unziping();
      
        obj.unzip(new File("C:\\MY\\Code\\com.zip"),"C:\\MY\\Code");
    }

}

JSP : Simple File Uploading Codes.

We will see how to upload a file using JSP, you can upload a file to your desire location with desire name. Please see the simple self explanatory codes below.

Please add below mentioned jar files in your applications classpath.





1st HTML interface (can be used in JSP as well)

FileUploadingInterface.HTML


<HTML>
<HEAD>
<TITLE>File Uploading Interface</TITLE>
</HEAD>
<BODY>
<center>
<h3>Simple File Uploading Example</h3>
<form action="ProcessUploadedFile.jsp" method="post" enctype="multipart/form-data">
Name <input type="text" name="userName"> (optional) </br></br>
File <input type="file" name="file1"> </br></br> <!-- Here You Can Add more numbers of Files For Uploading -->
<input type="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>



2nd JSP code


ProcessUploadedFile.jsp


<%@ page import="java.io.*" %>
<%@ page import="java.util.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (!isMultipart)
{
}
else
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException e)
{
e.printStackTrace();
}

Iterator itr = items.iterator();

while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();

//Get Other Form Fileds Values in this Block
if (item.isFormField())
{
String itemName = item.getFieldName();
String itemValue = item.getString();
String name = "";
if (itemName.equals("userName"))
name = item.getString();

out.println("User Name "+name);
}
//Get File type Values Here, it could be one or multiple File
else
{
try
{
String itemName = item.getName();

//userFieldName is what u provided in html file
String userFieldName = item.getFieldName();

if(itemName != null)
{
if(itemName.equals(""))
{
//If Nothing Uploaded
out.println("No File Uploaded");
}
else
{
//Provide Destination Folder, Where Uploaded File to be saved
boolean folderMade = (new File("d:/UploadedFileFolder")).mkdirs();

// This is required to filter out file name from complete file path.
int idx = itemName.lastIndexOf("\\");

String filename = "";

if(idx > -1)
{
//in case of IE, it sends complete path. Hence only file name must be filtered out.
idx=idx+1;
filename = itemName.substring(idx);
}
else
{
//in case of other borwsers, its just filename
filename = itemName;
}

File savedFile = new File("d:/UploadedFileFolder/"+filename);
item.write(savedFile);

//Get path of the saved file
String path = savedFile.getPath();

out.println("File Uploaded Sucessfully "+path);

}
}
}//try
catch(Exception e)
{
e.printStackTrace();
}
}//else
}//while
}//else
%>

Java : Simple program to copy Directory (subdirectories and files) from specified source to specified destination.

Here is the code of the program :




import java.io.*;
import java.text.SimpleDateFormat;

public class DirectoryCopier
{
public static void main(String[] args) throws IOException
{
//Creating instance of DirectoryCopier
DirectoryCopier cd = new DirectoryCopier();

//Specifying Source Directory
String source = "D:\\Blog";

//Creating File of source directory
File src = new File(source);

//Specifying Destination Directory
String destination = "C:\\copyOfBlog";

File dst = new File(destination);

//Calling method DirectoryCopier with source and destination
cd.DirectoryCopier(src, dst);
}

public void DirectoryCopier(File srcPath, File dstPath) throws IOException
{
//If Source is a Directory
if (srcPath.isDirectory())
{
System.out.println(srcPath + "is directory.");

//If Destination directory not exists, create it
if (!dstPath.exists())
{
System.out.println("calling mkdir " + dstPath);
dstPath.mkdir();
}

//Get All Available Files in this source directory
String files[] = srcPath.list();

//Iterate each file
for(int i = 0; i < files.length; i++)
{
System.out.println("--Source "+srcPath);
System.out.println("--Destination "+dstPath);

//Recursively calling DirectoryCopier
DirectoryCopier(new File(srcPath, files[i]),new File(dstPath, files[i]));
}
}
//If Source is a leaf node
else
{
//If Source does not exists print it and exit
if(!srcPath.exists())
{
System.out.println("File or directory does not exist.");
System.exit(0);
}
else
{
System.out.println("Source "+srcPath);
System.out.println("Destination "+dstPath);

//Copying by bytes
FileInputStream in = new FileInputStream(srcPath);
FileOutputStream out = new FileOutputStream(dstPath);

// Transfer bytes from in to out
byte[] buf = new byte[1024];

int len;

while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}

in.close();
out.close();
}

}
System.out.println("Directory copied.");
}
}

Java: Simple Program To Read Excel File

There are two simple methods, Below both programs produces same output

1st Method : Using POI (Note : Download POI to run this code)


import java.io.*;
import java.util.*;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;

public class ExcelReadIterator
{
public static void main(String[] args) throws Exception
{
InputStream ExcelFileToRead = new FileInputStream("ExcelFile.xls");
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);

HSSFSheet sheet=wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;

Iterator rows=sheet.rowIterator();

while (rows.hasNext())
{
row=rows.next();
Iterator cells=row.cellIterator();
while (cells.hasNext())
{
cell=cells.next();

if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}

}
}




2nd Method : Using Virtual DB (This is simple method, directly u can run this code)



import java.sql.*;

public class ReadExcel
{
public static void main (String[] args)
{
String ExcelFileToRead = "ExcelFile.xls";

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ="+ExcelFileToRead);
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("Select * from [Sheet1$]");


while(rset.next())
{
System.out.println(rset.getString(1)+" "+rset.getString(2)+" "+rset.getString(3)) ;
}



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


}