Thursday, February 19, 2009

JSP : Write Log Datewise

Writing logs in JSP..

Here is the code you can use to write log Every day Datewise(dd-mm-yyyy).
You can use in in you code JSP or Servlet.

you need to import following

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

Add following lines in your code accordingly


// open file to write date wise logs
SimpleDateFormat df = new SimpleDateFormat("dd-MMMM-yyyy");
java.util.Date date = new java.util.Date();
String today = df.format(date);

//Provide file in which log to be written
BufferedWriter outlog = outlog = new BufferedWriter(new FileWriter("D:\\Log_"+today+".log", true));

outlog.write("1st Line \n");........... //used "\n" as line seperator
outlog.write("2nd Line ");
outlog.newLine(); .....................//used outlog.newLine() as line seperator
outlog.write("3rd Line ");


//flush BufferedWriter at the end
outlog.flush();
outlog.close();

Wednesday, February 11, 2009

Java : Sorting ArrayList in Ascending and Descending order

Simple Program to sort Arraylist in Ascending and Descending order. U can also sort String,Float,Double.. etc in ArrayList.

ArrayList can be sorted using inbuilt java 1.5 class method Collections.sort(..).

Here is code, save it as file : Sorting.java


import java.util.*;

public class Sorting
{
public static void main(String[] args)
{
//Initilize ArrayList
ArrayList<Integer> arrayList = new ArrayList<Integer>();//also it can sort String,Float,Double.. etc

//creating Random numbers
//Random is a inbuilt java class in 1.5 in util package
Random random = new Random();

//putting Values
for(int i=1;i<=10;i++)
{
int temp = random.nextInt(100);//get random int values between 0 and 100
arrayList.add(temp);
}

//Sorting ArrayList
System.out.println("Before Sorting..");
System.out.println(arrayList);

Collections.sort(arrayList);//Sorting using sort method, default ascending sort

System.out.println("After Sorting Ascending..");
System.out.println(arrayList);

//useing Comparator to sort in descending order
Comparator<Integer> comparator = Collections.reverseOrder();
Collections.sort(arrayList,comparator);//Descending sorting using sort method

System.out.println("After Sorting Descending..");
System.out.println(arrayList);
}
}

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
%>