Powered by Blogger.

Copying the data from one file to another file using IO Streams.

>> Friday, April 29, 2011

Copying the data from one file to another file using IO Streams_JavabynataraJ
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();

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

>> Thursday, April 28, 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 '.

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

>> Wednesday, April 27, 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();
        }
    }
}



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();
        }
    }
}


Download Spring material from DurgaSoft

>> Saturday, April 23, 2011


Download Spring notes from Durgasoft_JavabynataraJ



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

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

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.

1). Introduction to Streams

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.


Singleton Design Pattern Example Program

>> Tuesday, April 19, 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");
    }
}
Reference books:

  • Design Patterns : Elements of Reusable Object 

  • DESIGN PATTERNS IN JAVA 2nd  Edition 

  • Data Structures And Algorithms With Object-oriented Design Patterns In Java 1st Edition 

  • Dependency Injection: Design Patterns Using Spring and Guice
  • What is Deserialization in java ? Write a simple program using Deserialization?

    >> Monday, April 18, 2011

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

    Program for User defined Exception in java

    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)

    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."

    Serialization in Java with Simple program_JavabynataraJ

    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.

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

    >> Tuesday, April 12, 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.

    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.
    JDBC Type Driver 1

    JDBC - CallableStatement IN, OUT, INOUT parameters

    >> Friday, April 8, 2011

    Callable Statement in Brief_JavabynataraJThe 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.

    JDBC - Simple Statement

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

    Related Posts Plugin for WordPress, Blogger...
    © javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.