6). Copying the data from one file to another file using java Streams.

>> Friday, April 29, 2011

Here the task is we have to understand  Copying the data from one file to another file.So the data should be serialized first and then by doing deserialization of same file and again serialize with different file name.


#1). Write the data into a file "hello2.dat".



FileOutputStream fos = new FileOutputStream("hello2.dat");
            byte b[] = str.getBytes();
            fos.write(b);
            fos.close();

Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

5 ).Write a program to read a file by sending the argument as a file name at runtime.

>> Wednesday, April 27, 2011

Here we are using BufferedReader to read the name of the file.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


Read the file using FileInputStreamReader then send it to BufferedInputStreamReader to read all the data with InputStreamReader provided mehtods.



package javabynataraj.iopack;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileArgs {
    public static void main(String[] args)throws IOException {
        int ch;
        String fname;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter file name: ");
        fname = br.readLine();
        FileInputStream fis = new FileInputStream(fname);
        BufferedInputStream bis = new BufferedInputStream(fis);
        while((ch=bis.read())!=-1){
            System.out.print((char)ch);
        }
        fis.close();
        bis.close();

    }
}


Note:
You should have one serialized file or any file to enter the name at runtime .you should enter filename with extension like ' hello.dat '.

Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

4 ). Program to persist the data into a file using BufferedOutputStream

>> Tuesday, April 26, 2011

#1). Buffered classes are used to increase the performance of the application.

BufferedOutputStream working flow
#2). When ever the Buffered Classes are used by default a small amount of memory will be created with the size of 512 bytes.

#3). The data need to be written into a file, first data will be stored in the buffer then the entire data will be dumped to a file.(present with in the buffer).

#4). For each FileInputStream class there will be associated BufferedInputStream class.

String str="hi this is muralidhar";
     FileOutputStream fos=new FileOutputStream("hello.dat");


#5). These BufferedStream classes will take the other stream classes objects as an arguments.


BufferedOutputStream bos = new BufferedOutputStream(fos);


read the file and save into array of bytes  using getBytes( ) method.

and write the  object into the bos object.


package javabynataraj.iopack;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferedOutput {
    public static void main(String[] args) {
        String str="hi this is muralidhar";
        try{
            FileOutputStream fos=new FileOutputStream("hello.dat");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            byte by[] = str.getBytes();
            bos.write(by);
            bos.close();
            fos.close();
            System.out.println("Done........!");
        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
    }
}



Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

3). Write a program to write the data into a file by using FileOutputStream reader

By using FileOutputStream class we have to create an object by passing the argument as a file.

Then read the content in a file using getBytes[] method.


obj.getBytes[];


then by using FileOutputStreamReader class object write the data of bytes array object.

Check out the below code for this program.


package javabynataraj.iopack;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutput {
    public static void main(String[] args) {
        String str = "Hello how are you";
        try{
            FileOutputStream fos = new FileOutputStream("stud.dat");
            byte b[] = str.getBytes();
            fos.write(b);
            fos.close();
            System.out.println("Hello World");
        }catch(IOException ioe){
            ioe.printStackTrace();
        }
    }
}


Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

Download Spring material from DurgaSoft

>> Saturday, April 23, 2011





Download the spring meterial from Durga soft with pdf document.

Requirements to run SPRING




SPRING runs either on Linux or Windows system. The minimum requirements for running on Windows are:
An IBM-PC compatible, at least 512 Mb RAM, processor speed 500 MHz or better

  • Hard disk: 200 MB for the software and 250 MB for examples;
  • Windows 95/98/ME/NT/XP/Vista/W7.
  • The requirements for Linux are:
  • Memory (RAM): 512Mb or more.
  • Hard disk: 200 MB free for the software and 250 Mb or more for examples.
  • Linux Operational Systems: Fedora8, Mandriva2008, OpenSuse10/11 and Ubuntu7/8

Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

Thread Synchronization in java (ebook download)


If a Java class has synchronized methods, each object of the class behaves like a monitor: The synchronized methods guarantee mutual exclusion of the accessing threads. A thread can wait for a condition within a synchronized method until another thread notifies the waiting thread that the condition may be fulfilled..


For more information see this

Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

2). Streams vs Reader & Writer

>> Friday, April 22, 2011

Streams

To Write the data into file OutputStreamReader and  to read the data from a file, the class InputStreamReader will be used.

InputStream classes are used to read the data.

OutputStream classes are used to write the data.

The above all defined classes are byte oriented classes

Reader & Writer

The Character oriented classes are the reader and writer classes.These are also defined in an IO Package.These are also the abstract classes.

FileReader class comes under the InputStreamReader class.

FileWriter class comes under the OutPutStreamWriter class.

To Identify the difference between Byte oriented classes and Character oriented class is..
 
  #1). If the class name ends with the word Stream then it is a Byte Oriented class

  #2). If the class name ends with the word Reader or Writer then it is a Character oriented class.

Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

1). Introduction to Streams

>> Thursday, April 21, 2011

A Stream represents flow of data mainly streams are used to move the data from input device to output device,or a file or file to output device or file to file.

When ever data need to be transferred then a user need to have the address of the source and the address of the destination. To get the address of the source or destination , a user can make use of some of the Stream classes.

Example:
   
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


InputStreamReader Class will return the address of the standard input device and this class takes an argument as System.in

System is a class which contains a static variable in which represents the standard input device like keyboard.

BufferedReader class Object expects the object of InputStreamReader class as an argument which contains the address of the input device.


Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

Singleton Design Pattern Example Program

>> Monday, April 18, 2011

Singleton Design pattern will allow only one object per Class(JVM).

Before Writing Singleton Design pattern you should follow these steps.

#1). create an instance as static and return type as The same class, and it should be assigned as null.

private static Singletonn instance = null;

#2). "Create a Constructor as private" to deny the creation of object from other class.

private Singletonn(){
        
    }

#3). Write a static method to create object for our class.It should be Once for a class.

public static Singletonn getInstance(){

}

#4). At last return the class Object.

Here We are creating the object once only not again and again.The first time created object is returning again when you called.

package javabynataraj.basic;

class Singletonn {
    private static Singletonn instance = null;
    private Singletonn(){
        
    }
    public static Singletonn getInstance(){
        if(instance==null){
            instance = new Singletonn();
        }
        return instance;
    }
}

public class Singleton{
    public static void main(String[] args) {
        System.out.println("before calling ...");
        System.out.println(Singletonn.getInstance());
        System.out.println("Once Called");
        System.out.println(Singletonn.getInstance());
        System.out.println("Second time called");
    }
}


For Refernce books:

Design Patterns: Elements of Reusable Object-Oriented SoftwareSOA Design Patterns (The Prentice Hall Service-Oriented Computing Series from Thomas Erl)

Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

What is Deserialization in java ? Write a simple program using Deserialization?

Deserialization is a process of converting the data from files or database converting to Stream of bytes using class Objects.


The Deserialization can be done after serializing the data only.Then we can read the data from the serialized files.

Convert your Serialized file into file form.


File fromFile = new File("Emp.ser");



By using the below two classes we can do the process of deserialization.

#1. FileInputStream
#2. ObjectInputStream

A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.


FileInputStream fis = new FileInputStream(fromFile);


An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. This can be Converts the Serialized file into the Object form.


ObjectInputStream ois = new ObjectInputStream(fis);


To get the object of a serialized file we have to typecast into our class Employee to read the values in a file using variable names.


Employee emp = (Employee) ois.readObject();


After that close all the object connections.

You should write the  Employee class already written in Serialization.(check it there) 

Program for Deserialization:


package javabynataraj.iopack;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class Deserial {
    public static void main(String arg[]) {
        File fromFile = new File("Emp.ser");
        try {
            FileInputStream fis = new FileInputStream(fromFile);
            ObjectInputStream ois = new ObjectInputStream(fis);
            Employee emp = (Employee) ois.readObject();
            System.out.println("Deserialized data: \n"+ emp.eno + " "+ emp.ename +" "+ emp.esal+" "+emp.eaddr+ "  from Emp.ser");
            ois.close();
        } catch(IOException e) {
            System.out.println("Deserialization failed");
            System.out.println(e);
            System.exit(1);
        } catch(ClassNotFoundException e) {
            System.out.println("Deserialization failed");
            System.out.println(e);
            System.exit(1);
        }
    }
}

Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

Program for User defined Exception in java

>> Sunday, April 17, 2011

To create user defined exception first you should create a class by extending Exception class.

class BadString extends RuntimeException{

}

Create  another class  named as "UserExcep" to throw our own exception.

public class UserExcep


Write some logical conditions to throw your exception and the exception caught by catch block.

package javabynataraj.exceptions;

import java.io.BufferedReader;
import java.io.InputStreamReader;

class BadString extends RuntimeException{

}
public class UserExcep{
    public static void main(String[] args) {
        try{
            System.out.println("Enter the String: ");
            BufferedReader sb=new BufferedReader(new InputStreamReader(System.in));
            String s=sb.readLine();
            if(s.equals("hateyou")){
                throw new BadString();
            }
            System.out.println("I Accept your String");
        }catch(Exception e){
            System.out.println("Please enter a good String");
            //e.printStackTrace();
        }
    }
}


Introduction to Java Programming, Comprehensive (8th Edition)

Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

What is Serialization? Write a Simple program in java using Serialization?

>> Saturday, April 16, 2011

"Serialization is the process of converting the data(Objects) into stream of bytes and storing in to the files or database."



We can do the Serialization process by implementing Serializable interface.


class SerialDemo implements java.io.Serializable.

The above step tells the compiler that you are going to implement serialization.
Which basically means that the object is going to be saved or persisted.

use FileOutputStream class and ObjectOutputStream class.

FileOutuptStream Creates an output file stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection.

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be write using an ObjectOutputStream.

Save the file using
writeObject(obj);

Program for Serialization


What if you have something top secret, like your password which should not be saved. You mark it as transient!

transient int i;

Create a class Employee to collect information.

package com.javabynataraj.iopack;

class Employee implements java.io.Serializable {
   
 public String name;
 public String address;
 public transient int SSN;
 public int number;

 public void mailCheck() {
    System.out.println("Mailing a check to " + name + " " + address);
  }
}

then create a main class to persist the Employee details in a file.

package com.javabynataraj.iopack;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Serial {
 public static void main(String[] args) {
  Employee e = new Employee();
  e.name = "Muralidhar";
  e.address = "JavabynataraJ,SatyaTechnologies";
  e.SSN = 11111;
  e.number = 101;
  try {
   System.out.println("Before Serialization");
   FileOutputStream fileOut = new FileOutputStream("employee.ser");
   ObjectOutputStream out = new ObjectOutputStream(fileOut);
   out.writeObject(e);
   out.close();
   fileOut.close();
   System.out.println("End of Serialization");
  } catch (IOException i){
   i.printStackTrace();
  }
 }
}

Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

Upload CSV file into MySql Database based on columns using Servlets and Java

>> Monday, April 11, 2011

The CSV file is having multiple values to insert in perticular columns and rows in mysql database.

Here we have two files so we have to insert in two tables .

*** one is Header part file

*** another is Detail part file

Basically these two are to upload the questions and answers into the examination portal to upload question papers and answer paper in (Merit Tracking System project).

First we have to do the things are Uploaded file has to save in perticular folder and then they have to insert the values into the database table.This is our main task to do.

Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

Types of JDBC Drivers

>> Saturday, April 9, 2011

JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

4 types of jdbc drivers are elaborated in detail as shown below:

Type 1 JDBC Driver

JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.
Type 1: JDBC-ODBC Bridge
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database’s ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.

Type 2 JDBC Driver

Native-API/partly Java driver
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native api.
Type 2: Native api/ Partly Java Driver
Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.

Type 3 JDBC Driver

All Java/Net-protocol driver
Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.
Type 3: All Java/ Net-Protocol Driver
Advantage
1. This driver is server-based, so there is no need for any vendor database library to be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantage
It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.

Type 4 JDBC Driver

Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the database server.
Type 4: Native-protocol/all-Java driver
Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don’t have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.



Read more...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

JDBC - CallableStatement

>> Friday, April 8, 2011

The CallableStatement interface allows the use of SQL statements to call stored procedures. Stored procedures are programs that have a database interface. These programs possess the following:
1)    They can have input and output parameters, or parameters that    are   both input and output.
2)    They can have a return value.
3)    They have the ability to return multiple ResultSets.

        Conceptually in JDBC, a stored procedure call is a single call to the database, but the program associated with the stored procedure may process hundreds of database requests. The stored procedure program may also perform a number of other programmatic tasks not typically done with SQL statements.

        Creating CallableStatements

        The prepareCall method is used to create new CallableStatement objects. As with the prepareStatement method, the SQL statement must be supplied at the time that the CallableStatement object is created. At that time, the SQL statement is precompiled. For example, assuming a Connection object named conn already exists, the following creates a CallableStatement object and completes the preparation phase of getting the SQL statement ready for processing within the database:

           
        PreparedStatement ps = conn.prepareStatement("? = CALL ADDEMPLOYEE(?, ?, ?");


        Handling parameters

        As stated, CallableStatement objects may take three types of parameters:

            IN

            IN parameters are handled in the same manner as PreparedStatements. The various set methods of the inherited PreparedStatement class are used to set the parameters.

            OUT

            OUT parameters are handled with the registerOutParameter method. The most common form of registerOutParameter takes an index parameter as the first parameter and an SQL type as the second parameter. This tells the JDBC driver what to expect for data from the parameter when the statement is processed. There are two other variations on the registerOutParameter method that can be found in the java.sql package Javadoc.

            INOUT

            INOUT parameters require that the work for both IN parameters and OUT parameters be done. For each INOUT parameter, you must call a set method and the registerOutParameter method before the statement can be processed. Failing to set or register any parameter results in an SQLException being thrown when the statement is processed.

        Using CallableStatement methods to call stored procedures

        To call stored procedures, you invoke methods in the CallableStatement class. The basic steps are:

        --->Invoke the Connection.prepareCall method to create a CallableStatement object.
        --->Invoke the CallableStatement.setXXX methods to pass values to the input (IN) parameters.
        --->Invoke the CallableStatement.registerOutParameter method to indicate which parameters are output-only (OUT) parameters, or input and output (INOUT) parameters.
        --->Invoke one of the following methods to call the stored procedure: 
        --->CallableStatement.executeUpdate
        --->Invoke this method if the stored procedure does not return result sets.
        --->

        1. --->CallableStatement.executeQuery
          Invoke this method if the stored procedure returns one result set.
          CallableStatement.execute
          Invoke this method if the stored procedure returns multiple result sets.



        2. --->If the stored procedure returns result sets, retrieve the result sets. See Retrieve multiple result sets from a stored procedure in a JDBC application.



        3. --->Invoke the CallableStatement.getXXX methods to retrieve values from the OUT parameters or INOUT parameters.



        4. --->Invoke the CallableStatement.close method to close the CallableStatement object when you have finished using that object.



        The following code illustrates calling a stored procedure that has one input parameter, four output parameters, and no returned ResultSets. The numbers to the right of selected statements correspond to the previously-described steps.

        Read more...

        Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

        JDBC - Simple Statement

        >> Thursday, April 7, 2011

        The Statement interface lets you execute a simple SQL statement with no parameters. The SQL instructions are inserted into the Statement object when the Statement.executeXXX method is called.

        Query Statement: This code segment creates a Statement object and calls the Statement.executeQuery method to select text from the dba database. The results of the query are returned in a ResultSet object. How to retrieve results from a ResultSet object is explained in Result Sets below.



        Statement stmt = con.createStatement();
         ResultSet results = stmt.executeQuery("SELECT TEXT FROM dba ");


        Update Statement: This code segment creates a Statement object and calls the Statement.executeUpdate method to add an email address to a table in the dba database.

          String updateString =  "INSERT INTO dba VALUES (some text)";
          int count = stmt.executeUpdate(updateString);

        Read more...

        Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

        Related Posts Plugin for WordPress, Blogger...

        Random Posts

        JavabynataraJ - Find me on Bloggers.com Find me on blorner.com Technology Blogs JavabynataraJ Backlinks Blogarama - The Blog Directory

          © Blogger template Webnolia by Ourblogtemplates.com 2009

        Back to TOP