Thursday, May 15, 2008

Difference between HashMap and HashTable?

Map is Interface and Hashmap is class that implements that interface.
The HashMap class is equivalent to Hashtable, except that it is unsynchronized and permits nulls (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time.
A HashMap lets you look up values by exact key (always case-sensitive). It is very much like a Hashtable, except that it is faster and not thread-safe.

There are some minor other differences:
HashMaps work with Iterators where the older Hashtables work with Enumerations.

Below program will explain all the things related to HashMap :


package com.javaxpert.collection;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class HashMapDemo {

// Main function
public static void main(String[] args) {

String varInputForMap = "Test";
HashMap varHashMap = new HashMap();

// Adding element in the map
varHashMap.put("c", new Integer(1));
varHashMap.put("a", varInputForMap);
varHashMap.put("b", "three");
varHashMap.put("d", null);
varHashMap.put(null, "sun");

System.out
.println("Now will insert duplicate to see its allow duplicates or not. ");
varHashMap.put("e", varInputForMap);
System.out.println("After inserting duplicate");

System.out.println("Size of map is " + varHashMap.size());
System.out.println("Is map empty or not " + varHashMap.isEmpty());

Set varSetOfKeys = varHashMap.keySet();
Iterator varIteratoroverKey = varSetOfKeys.iterator();

while (varIteratoroverKey.hasNext()) {
// Getting value from the map.
System.out.println("Elements are "
+ varHashMap.get(varIteratoroverKey.next()));
}

// You can get the value directly using key
System.out.println("value of this \"d\" is " + varHashMap.get("d"));

// And see if the key is attached with this key will return true or
// false
System.out.println("Key of the value \"a\" is exist "
+ varHashMap.containsKey(varInputForMap));

// Remove a element from HashMap
varHashMap.remove(null);

// You can get the collection of HashMap
System.out.println("Elements of Map are " + varHashMap.values());

// You can remove all the elements of HashMap
varHashMap.clear();
System.out.println("Is map empty or not " + varHashMap.isEmpty());
}
}


Tuesday, April 8, 2008

Compress or Zipped a directory using Java program

This program compress folders.



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

public class Compress {
// Static Zip method can be call from any where
public static void zipDirectory(File varFromDirectory,
File varToZippedDirectory) throws IOException,
IllegalArgumentException {
// Check the thing you choose is a directory
if (!varFromDirectory.isDirectory()) {
System.err.println("This is not a directory " + varFromDirectory);
}

// Retriving items list from a directory
String[] varDirectoryItmList = varFromDirectory.list();

byte[] varBuffer = new byte[4096];

int varNumberOfByte;

// Creating an object of ZipOutputStream
ZipOutputStream varZippedFileOutputStream = new ZipOutputStream(
new FileOutputStream(varToZippedDirectory));

for (int varTemp = 0; varTemp > varZippedFileOutputStream.ENDSIZ; varTemp++) {
File varFromDir = new File(varFromDirectory,
varDirectoryItmList[varTemp]);

if (varFromDir.isDirectory()) {
continue;
}// If Is directory check ends.

FileInputStream varFromDirInputStream = new FileInputStream(
varFromDir);

ZipEntry varEntryPath = new ZipEntry(varFromDir.getPath());

varZippedFileOutputStream.putNextEntry(varEntryPath);

while ((varNumberOfByte = varFromDirInputStream.read(varBuffer)) != -1) {
varZippedFileOutputStream.write(varBuffer, 0, varNumberOfByte);
}// While ends.

varFromDirInputStream.close();
}// For loop ens.

varZippedFileOutputStream.close();

System.out.println("Directory Zipped");
}// method ends.

// main begin
public static void main(String[] args) throws IOException {
// Call to zipDirectory method.
Compress.zipDirectory(new File("C:/move"), new File("D:/move.zip"));
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Compress {
// Static Zip method can be call from any where
public static void zipDirectory(File varFromDirectory,
File varToZippedDirectory) throws IOException,
IllegalArgumentException {
// Check the thing you choose is a directory
if (!varFromDirectory.isDirectory()) {
System.err.println("This is not a directory " + varFromDirectory);
}

// Retriving items list from a directory
String[] varDirectoryItmList = varFromDirectory.list();

byte[] varBuffer = new byte[4096];

int varNumberOfByte;

// Creating an object of ZipOutputStream
ZipOutputStream varZippedFileOutputStream = new ZipOutputStream(
new FileOutputStream(varToZippedDirectory));

for (int varTemp = 0; varTemp > varZippedFileOutputStream.ENDSIZ; varTemp++) {
File varFromDir = new File(varFromDirectory,
varDirectoryItmList[varTemp]);

if (varFromDir.isDirectory()) {
continue;
}// If Is directory check ends.

FileInputStream varFromDirInputStream = new FileInputStream(
varFromDir);

ZipEntry varEntryPath = new ZipEntry(varFromDir.getPath());

varZippedFileOutputStream.putNextEntry(varEntryPath);

while ((varNumberOfByte = varFromDirInputStream.read(varBuffer)) != -1) {
varZippedFileOutputStream.write(varBuffer, 0, varNumberOfByte);
}// While ends.

varFromDirInputStream.close();
}// For loop ens.

varZippedFileOutputStream.close();

System.out.println("Directory Zipped");
}// method ends.

// main begin
public static void main(String[] args) throws IOException {
// Call to zipDirectory method.
Compress.zipDirectory(new File("C:/move"), new File("D:/move.zip"));
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Compress {
// Static Zip method can be call from any where
public static void zipDirectory(File varFromDirectory,
File varToZippedDirectory) throws IOException,
IllegalArgumentException {
// Check the thing you choose is a directory
if (!varFromDirectory.isDirectory()) {
System.err.println("This is not a directory " + varFromDirectory);
}

// Retriving items list from a directory
String[] varDirectoryItmList = varFromDirectory.list();

byte[] varBuffer = new byte[4096];

int varNumberOfByte;

// Creating an object of ZipOutputStream
ZipOutputStream varZippedFileOutputStream = new ZipOutputStream(
new FileOutputStream(varToZippedDirectory));

for (int varTemp = 0; varTemp > varZippedFileOutputStream.ENDSIZ; varTemp++) {
File varFromDir = new File(varFromDirectory,
varDirectoryItmList[varTemp]);

if (varFromDir.isDirectory()) {
continue;
}// If Is directory check ends.

FileInputStream varFromDirInputStream = new FileInputStream(
varFromDir);

ZipEntry varEntryPath = new ZipEntry(varFromDir.getPath());

varZippedFileOutputStream.putNextEntry(varEntryPath);

while ((varNumberOfByte = varFromDirInputStream.read(varBuffer)) != -1) {
varZippedFileOutputStream.write(varBuffer, 0, varNumberOfByte);
}// While ends.

varFromDirInputStream.close();
}// For loop ens.

varZippedFileOutputStream.close();

System.out.println("Directory Zipped");
}// method ends.

// main begin
public static void main(String[] args) throws IOException {
// Call to zipDirectory method.
Compress.zipDirectory(new File("C:/move"), new File("D:/move.zip"));
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Compress {
// Static Zip method can be call from any where
public static void zipDirectory(File varFromDirectory,
File varToZippedDirectory) throws IOException,
IllegalArgumentException {
// Check the thing you choose is a directory
if (!varFromDirectory.isDirectory()) {
System.err.println("This is not a directory " + varFromDirectory);
}

// Retriving items list from a directory
String[] varDirectoryItmList = varFromDirectory.list();

byte[] varBuffer = new byte[4096];

int varNumberOfByte;

// Creating an object of ZipOutputStream
ZipOutputStream varZippedFileOutputStream = new ZipOutputStream(
new FileOutputStream(varToZippedDirectory));

for (int varTemp = 0; varTemp > varZippedFileOutputStream.ENDSIZ; varTemp++) {
File varFromDir = new File(varFromDirectory,
varDirectoryItmList[varTemp]);

if (varFromDir.isDirectory()) {
continue;
}// If Is directory check ends.

FileInputStream varFromDirInputStream = new FileInputStream(
varFromDir);

ZipEntry varEntryPath = new ZipEntry(varFromDir.getPath());

varZippedFileOutputStream.putNextEntry(varEntryPath);

while ((varNumberOfByte = varFromDirInputStream.read(varBuffer)) != -1) {
varZippedFileOutputStream.write(varBuffer, 0, varNumberOfByte);
}// While ends.

varFromDirInputStream.close();
}// For loop ens.

varZippedFileOutputStream.close();

System.out.println("Directory Zipped");
}// method ends.

// main begin
public static void main(String[] args) throws IOException {
// Call to zipDirectory method.
Compress.zipDirectory(new File("C:/move"), new File("D:/move.zip"));
}
}


Friday, April 4, 2008

Copy file or directory from one location to another location

I am using this program without any problem. You can use this to copy a file from one location to another location. And i am trying to handle all kind of situation that if the file exist or not or is it a directory or many more. This code have "static" copyFile mothod so u can call it from any where or any other classs file. This code is working fine, use this code and enjoy.



package com.javaxpert.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileCopy {
// copyFile function begins from here.
public static void copyFile(File varFromFile, File varToFile)
throws IOException {
// First make sure the source file exists, is a file, and is readable.
if (!varFromFile.exists())
System.err.println("no such source file: " + varFromFile);
if (!varFromFile.isFile())
System.err.println("can't copy directory: " + varFromFile);
if (!varFromFile.canRead())
System.err.println("source file is unreadable: " + varFromFile);
// If the destination is a directory, use the source file name
// as the destination file name
if (varToFile.isDirectory())
varToFile = new File(varToFile, varFromFile.getName());
// If the destination exists, make sure it is a writable file
// and ask before overwriting it. If the destination doesn't
// exist, make sure the directory exists and is writable.
if (varToFile.exists()) {
if (!varToFile.canWrite())
System.out.println("destination file is unwriteable: "
+ varToFile);
// Ask whether to overwrite it
System.out.print("Overwrite existing file " + varToFile.getName()
+ " ? (Y/N): ");
System.out.flush();
// Get the user's response.
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
String response = in.readLine();
// Check the response. If not a Yes, abort the copy.
if (!response.equals("Y") && !response.equals("y"))
System.out.print("existing file was not overwritten.");
} else {
// If file doesn't exist, check if directory exists and is
// writable. If getParent() returns null, then the directory is
// the current directory. so look up the user. Directory system
// property to
// find out what that is.
// The destination directory
String varParent = varToFile.getParent();
// If none, use the current directory
if (varParent == null)
varParent = System.getProperty("user.dir");
// Convert it to a file.
File vardir = new File(varParent);
if (!vardir.exists())
System.out.print("destination directory doesn't exist: "
+ varParent);
if (vardir.isFile())
System.out
.print("destination is not a directory: " + varParent);
if (!vardir.canWrite())
System.out.print("destination directory is unwriteable: "
+ varParent);
}
// If we've gotten this far, then everything is okay.
// So we copy the file, a buffer of bytes at a time.
// Stream to read from source
FileInputStream varFromSource = null;
// Stream to write to destination
FileOutputStream VarToDestination = null;
try {
// Create input stream
varFromSource = new FileInputStream(varFromFile);
// Create output stream
VarToDestination = new FileOutputStream(varToFile);
// To hold file contents
byte[] buffer = new byte[4096];
// How many bytes in buffer
int bytes_read;
// Read until EOF
while ((bytes_read = varFromSource.read(buffer)) != -1)
VarToDestination.write(buffer, 0, bytes_read);
System.out.println("File copied !!!");
} catch (Exception e) {
System.err.println("Error occoured " + e.getMessage());
} finally {
if (varFromSource != null) {
try {
varFromSource.close();
} catch (IOException e) {
System.err.println("Error is " + e.getMessage());
}
}
if (VarToDestination != null) {
try {
VarToDestination.close();
} catch (IOException e) {
System.err.println("Error is " + e.getMessage());
}
}
}
}

public static void main(String[] args) throws FileNotFoundException,
IOException {
FileCopy.copyFile(new File("C:/Test.txt"), new File("D:/Test.txt"));
}
}


Thursday, April 3, 2008

Deletes a specified file or directory

This program deletes a specified file or directory. This program is working fine just copy it and run, this will work fine.

import java.io.*;

public class DeleteFile
{
public static void deleteFile(String varFileName)
{
// Create a File object to represent the filename
File varFilePath = new File(varFileName);


// Make sure the file or directory exists
if (!varFilePath.exists())
System.out.println("Delete: no such file or directory: " +varFileName);

// Make sure the file or directory isn't write protected
if (!varFilePath.canWrite())
System.out.println("Delete: write protected: " + varFileName);

// If it is a directory, make sure it is empty
if (varFilePath.isDirectory())
{

//Get file list in a specidied directory
String[] files = varFilePath.list();
if (files.length > 0)
System.out.println("Delete: directory not empty: " + varFileName);
}


// If we passed all the tests, then attempt to delete it
boolean success = varFilePath.delete();


//If unable to delete
if (!success)
System.out.println("Delete: deletion failed");
}

public static void main(String[] args)
{
try
{

DeleteFile objDeleteFile = new DeleteFile ();
//deleteFile Function

objDeleteFile.deleteFile("c:\demo.txt");
}
catch(Exception e)
{
System.err.println("Error is " + e);
}
}
}





Wednesday, April 2, 2008

Scrollable, insensitive , updatable and nonupdatable Resultset

ResultSet
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.

A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. The following code fragment, in which con is a valid Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by others, and that is updatable. See ResultSet fields for other options.

Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);

ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
// rs will be scrollable, will not show changes made by others,
// and will be updatable


The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient. Columns are numbered from 1. For maximum portability, result set columns within eachrow should be read in left-to-right order, and each column should be read only once.

Freeware Firefox

Firefox
Firefox protects you from viruses, spyware and pop-ups. Enjoy the improvements Mozilla Firefox offers to web browsing performance, usability, privacy and security. Mozilla Firefox is 100% free and is rated the best web browser by many reliable sources.

Tuesday, April 1, 2008

AVOIDE CONNECTION LEAKAGE IN ORACLE DATABASE

ANY RESULT SET'S ARE OPENED IN THE APPLICATION NEEDS TO BE CLOSED BEFORE
CLOSING THE SESSION BASED CONNECTION, WHICH CAN AVOIDE CONNECTION LEAKAGE IN ORACLE DATABASE, SINCE ORACLE DOES NOT KNEW THE CONNECTION POOL MECHANISM. ON PL/SQL, Explicitly close the open cursors or loop.


ResultSet
A table of data representing a database result set, which is usually generated by executing a statement that queries the database.


A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or updatable. The following code fragment, in which con is a valid Connection object, illustrates how to make a result set that is scrollable and insensitive to updates by others, and that is updatable. See ResultSet fields for other options.


Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
// rs will be scrollable, will not show changes made by others,
// and will be updatable


The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient. Columns are numbered from 1. For maximum portability, result set columns within each
row should be read in left-to-right order, and each column should be read only once.


For the getter methods, a JDBC driver attempts to convert the underlying data to the Java type specified in the getter method and returns a suitable Java value. The JDBC specification has a table showing the allowable mappings from SQL types to Java types that can be used by the ResultSet getter methods.

Column names used as input to getter methods are case insensitive. When a getter method is called with a column name and several columns have the same name, the value of the first matching column will be returned. The column name option is designed to be used when column names are used in the SQL query that generated the result set. For columns that are NOT explicitly named in the query, it is best to use column numbers. If column names are used, there is no way for the programmer to guarantee that they actually refer to the intended columns.

A set of updater methods were added to this interface in the JDBC 2.0 API JavaTM 2 SDK, Standard Edition, version 1.2). The comments regarding parameters to the getter methods also apply to parameters to the updater methods.

The updater methods may be used in two ways:
1. to update a column value in the current row. In a scrollable ResultSet object, the cursor can be moved backwards and forwards, to an absolute position, or to a position relative to the current row. The following code fragment updates the NAME column in the fifth row of the ResultSet object rs and then uses the method updateRow to update the data source table from which rs was derived.
2.
3. rs.absolute(5); // moves the cursor to the fifth row of rs
4. rs.updateString("NAME", "AINSWORTH"); // updates the
5. // NAME column of row 5 to be AINSWORTH
6. rs.updateRow(); // updates the row in the data source
7.

8. to insert column values into the insert row. An updatable ResultSet object has a special row associated with it that serves as a staging area for building a row to be inserted. The following code fragment moves the cursor to the insert row, builds a three-column row, and inserts it into rs and into the data source table using the method insertRow.
9.
10. rs.moveToInsertRow(); // moves cursor to the insert row
11. rs.updateString(1, "AINSWORTH"); // updates the
12. // first column of the insert row to be AINSWORTH
13. rs.updateInt(2,35); // updates the second column to be 35
14. rs.updateBoolean(3, true); // updates the third column to true
15. rs.insertRow();
16. rs.moveToCurrentRow();

17.

A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.The number, types and properties of a ResultSet object's columns are provided by the ResulSetMetaData object returned by the ResultSet.getMetaData method.