Friday, 2 September 2016

BufferedInputStream

                                       BufferedInputStream

My previous articles over Byte and character streaming use unbuffered I/o . It means we are directly interacting with operating system for each read and write request and make the program less efficient since for each and every request lot of overhead is required which includes accessing of disk, network activity etc.
To reduce this efforts , Java provides a functionality ,Buffered Input and Output Stream will read and write data from a memory known as buffer .
In order to achieve this , here the unbuffered stream object is passed to the constructor for a buffered stream class.
Example to use buffered I/O:
inputStream = new BufferedInputStream(new FileInputStream("file.txt"));
outputStream = new BufferedOutputStream(new FileOutputStream("newfile.txt"));

BufferedInputStream

BufferedInputStream will read the data from a memory known as buffer

Methods available:

1)      int available() :This method returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

2)      void close() :This method closes this input stream and releases any system resources associated with the stream.

3)      void mark(int readlimit) :This method see the general contract of the mark method of InputStream.
ReadLimit -- number of bytes to be read before the mark position gets invalid

4)      boolean markSupported() :This method tests if this input stream supports the mark and reset methods.

5)      int read() :This method reads the next byte of data from the input stream.

6)      int read(byte[] b, int off, int len) :This method reads bytes from this byte-input stream into the specified byte array, starting at the given offset.

Here b refers to a byte array to be populated ,off means starts storing from the offset and len means number of bytes to read.
7)      void reset(): This method repositions this stream to the position at the time the mark method was last called on this input stream.

8)      long skip(long n) :This method skips over and discards n bytes of data from this input stream

Example 1:
package bufferedistream;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 *
 * @author shashank
 */
public class BufferedIStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        BufferedInputStream bis = null;
        int available=0;
        int i =0;
        try
        {
            bis = new BufferedInputStream(new FileInputStream("D:\\Articles\\filehandling\\FailedRecord.log"));
           
                available = bis.available();
                System.out.println("Available bytes:" + available);
                
            while((i=bis.read())!=-1)
            {
               
              System.out.print((char)i);
            }
            bis.close();
           
        }catch(Exception e){e.printStackTrace();}
       
    }
   
}






Example 2:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bufferedistream;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 *
 * @author shabhatn
 */
public class BufferedIStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        BufferedInputStream bis = null;
        int available=0;
        int i =0;
        Boolean bool;
        try
        {
            bis = new BufferedInputStream(new FileInputStream("D:\\Articles\\filehandling\\mark.txt"));
           
                available = bis.available();
                System.out.println("Available bytes:" + available);
                bool = bis.markSupported();
         System.out.println("Support for mark() and reset() : "+bool);
               
            System.out.println("Before mark" + (char)bis.read());
            System.out.println("Before mark" + (char)bis.read());
            System.out.println("Before mark" + (char)bis.read());
            bis.mark(1);//In other words, readlimit is a suggestion; the stream is free to under-promise and over-deliver
            System.out.println("Before mark" + (char)bis.read());
            bis.reset();
            System.out.println("Before mark" + (char)bis.read());
            System.out.println("Before mark" + (char)bis.read());
            bis.reset();
            System.out.println("Before mark" + (char)bis.read());
            System.out.println("Before mark" + (char)bis.read());
           
            bis.close();
           
        }catch(Exception e){e.printStackTrace();}
       
    }
   
}



Example 3:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bufferedistream;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 *
 * @author shabhatn
 */
public class BufferedIStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        BufferedInputStream bis = null;
        int available=0;
        int i =0;
        Boolean bool;
        try
        {
            bis = new BufferedInputStream(new FileInputStream("D:\\Articles\\filehandling\\mark.txt"));
           
                available = bis.available();
                System.out.println("Available bytes:" + available);
         byte [] arr = new byte[available];
        
         bis.read(arr,3,1);
        
         for(byte b:arr)
         {
             System.out.print((char)b);
         }
        
           
            bis.close();
           
        }catch(Exception e){e.printStackTrace();}
       
    }
   
}



Example 4:
*/
package bufferedistream;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

/**
 *
 * @author shabhatn
 */
public class BufferedIStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        BufferedInputStream bis = null;
        int available=0;
        int i =0;
        Boolean bool;
        try
        {
            bis = new BufferedInputStream(new FileInputStream("D:\\Articles\\filehandling\\mark.txt"));
           
                available = bis.available();
                System.out.println("Available bytes:" + available);
         byte [] arr = new byte[available];
        
       
         bis.skip(2);
        
        
             System.out.print((char)bis.read());
        
        
           
            bis.close();
           
        }catch(Exception e){e.printStackTrace();}
       
    }
   

}


DOM Parser

                                                       DOM Parser

DOM – Document Object Model
It Parse the document by loading the complete contents of the xml document along with its hierarchical tree in memory
We should use DOM parser when we need to learn about document Structure ,It provides an interface which enables the programs to access and update the style, structure and contents of XML documents. XML parsers that support the DOM will implements that interface.
XML File
<?xml version="1.0"?>
<company>
   <employee empid="393">
      <firstname>shashank</firstname>
      <lastname>bhatnagar</lastname>
      <nickname>shashank</nickname>
      <salary>85000</salary>
   </employee>
   <employee empid="493">
      <firstname>Raj</firstname>
      <lastname>Gupta</lastname>
      <nickname>Raju</nickname>
      <salary>95000</salary>
   </employee>
   <employee empid="593">
      <firstname>Deepak</firstname>
      <lastname>Kumar</lastname>
      <nickname>Deep</nickname>
      <salary>90000</salary>
   </employee>
</company>

Document Object Model Interfaces :
Node :  The base datatype of the model. 
  • In above example root node is company


Elements :  The vast majority of the objects .

ATTR :  It will represent an attribute of an element
  • In above example we will consider attribute as empid


Text :  The actual content of an element or an attribute

Document :  Represent entire XML document.

Common Document object model methods:
  1. Document.getDocumentElement() – it will return the root element of the document.
  2. Node.getFirstChild() – It will return the first child of a given Node.
  3. Node.getLastChild() – It will return the last child of a given Node.
  4. Node.getNextSibling() – It will return the next sibling of a given Node.
  5. Node.getPreviousSibling() – It will return the previous sibling of a given Node.
  6. Node.getAttribute(attrName) – it willl returns the attribute with the requested name for a given node.
Dom Parser steps :
Following are the steps used while parsing a document using DOM Parser.
1.   Import XML-related packages.
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
1.    Create a DocumentBuilder
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dbbuilder = dbfactory.newDocumentBuilder();
2.    Create a Document from a file or stream
File inputFile = new File("D://Articles//XML//company.xml");
Document doc = DBbuilder.parse(inputFile);
doc.getDocumentElement().normalize();
Normalize method : Normalize the root element of the XML document. This ensures that all Text nodes under the root node are put into a "normal" form, which means that there are neither adjacent Text nodes nor empty Text nodes in the document.
3.    Extract the root element
Element root = doc.getDocumentElement();
System.out.println("Root Element is " +  root.getNodeName());
Examine attributes
//returns specific attribute ---- getAttribute("attributeName");
System.out.println("Emplyee id :-" + element.getAttribute("empid"));
//returns a Map (table) of names/values --- getAttributes();
4.    Examine sub-elements
            //returns a list of subelements of specified name

NodeList nList = doc.getElementsByTagName("employee");

System.out.println("Salary is :-" + element.getElementsByTagName("salary").item(0).getTextContent());
The node list keeps itself up-to-date. If an element is deleted or added, in the node list or the XML document, the list is automatically updated.
Note: In a node list, the nodes are returned in the order in which they are specified in the XML document.

getChildNodes(); -- //returns a list of all child nodes 

                Java Program to read above XML
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package domxmlparser;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author shashank
 */
public class Domxmlparser {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try
        {
            File inputFile = new File("D://Articles//XML//company.xml");
            DocumentBuilderFactory DBfactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder DBbuilder = DBfactory.newDocumentBuilder();
            Document doc = DBbuilder.parse(inputFile);
            Element root = doc.getDocumentElement();
            System.out.println("Root Element is " +  root.getNodeName());
             NodeList nList = doc.getElementsByTagName("employee");
             System.out.println("*******");
             for(int temp=0;temp<nList.getLength();temp++)
             {
                 //Get the current node
                 Node Currentnode = nList.item(temp);
                 System.out.println("Current Element is :" + Currentnode.getNodeName());
                 if(Currentnode.getNodeType()==Node.ELEMENT_NODE)/*getNodeType()A code representing the type of the underlying object, as defined above.*/
                 {
                     Element element = (Element)Currentnode;
System.out.println("Emplyee id :-" + element.getAttribute("empid"));
   
System.out.println("First name is :-" + element.getElementsByTagName("firstname").item(0).getTextContent());
                    
System.out.println("Last name is :-" + element.getElementsByTagName("lastname").item(0).getTextContent());
                     
System.out.println("Nick name is :-" + element.getElementsByTagName("nickname").item(0).getTextContent());
                     
System.out.println("Salary is :-" + element.getElementsByTagName("salary").item(0).getTextContent());
                 }
             }
        }catch(Exception e){e.printStackTrace();}
    }
   


}


Java XML

                 Java XML Tutorial

XML referred to be as Extensible Markup Language. It’s a widely use mode of communication between two applications. Java provides a large set of libraries to parse, modify, create or query XML files.
XML is basically a text based language which is designed for communication between two applications, it stores and transport data in plain text form.
  1. XML is W3C recommendation for data storage and transport
  2. XML is a markup language
  3. XML is tag based language like HTML
  4. XML tags are not pre -defined , we can define our tags in XML unlike HTML
Pros and Cons of using XML
Pros:  
  1. It is easy to adapt and being plain text , XML can be used by any technology for data storage and transmission , hence it is technology independent.
  2. It is easy to read and understand.
  3. We can create our own custom tags
  4. Using  XSD , DTD and XML structure can be validated easily
Cons:
  1. XML file increases the transmission and storage costs
  2. It contains lot of repetitive terms
XML PARSERS
In order to access or modify data in XML , we need to traverse through the XML document.
XML Parsers provides way to access or modify data present in the XML document.
Please find the list if various types of parsers which are commonly use to parse XML documents
  1. DOM Parser : It parse the document by loading the complete contents of the xml document along with its hierarchical tree in memory
  2. SAX Parser : It parses the document on event based triggers and it doesn’t load complete document into the memory
  3. JDOM Parser:  It will be like DOM parser but it parses in more efficient way
  4. Stax Parser :  It will be like SAX parser but parses in more efficient way
  5. XPath Parser :  It will parses the XML based on expression
  6. DOM4J Parser :  A Java defined library which is used to parse XML,XPATH using collection framework.

We will discuss each parsers in details in our next articles

Thursday, 1 September 2016

CharacterStream:FileReader and FileWriter

Character Streams:

FileReader and FileWriter class
These classes are used to read and write character files respectively.
The java platform stores characters using Unicode conventions, Character stream I/O automatically translates this internal format to and from the local character set.
If at any point of time internationalization is required for your application and you had used character stream class , you application can adapt it without putting much efforts.
However java character streams are used to perform input and output for 16 bit Unicode.

FileWriter:
This class is used to write the data to a destination file

package filehandling_characterstream;

/**
 *
 * @author shashank
 */

import java.io.*;

public class FileHandling_CharacterStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       
        FileWriter fw = null;
       
        try
        {
            fw = new FileWriter("D://Articles//filehandling//filewritecharcters.txt");
            String s = "i am using character stream to write the data";
           
            char [] arr = s.toCharArray();
            fw.write(arr);
/*fw.write(s); we can directly pass string as well */
            fw.close();
            System.out.println("Success");
           
        }catch(Exception e){System.out.println(e);}
    }
   
}



FileReader:

This class is used to Read the data from a source file


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package filehandling_characterstream;

/**
 *
 * @author shashank
 */

import java.io.*;

public class FileHandling_CharacterStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       
        FileReader fr = null;
        int i=0;
       
        try
        {
            fr = new FileReader("D://Articles//filehandling//filewritecharcters.txt");
            while((i=fr.read())!=-1)
            {
                System.out.print((char)i);
                       
            }
            fr.close();
           
        }catch(Exception e){System.out.println(e);}
    }
   
}

Write a program to copy data from one file to another file
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package filehandling_characterstream;

/**
 *
 * @author shashank
 */

import java.io.*;

public class FileHandling_CharacterStream {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       
        FileReader fr = null;
        FileWriter fw = null;
        int i=0;
       
        try
        {
            fr = new FileReader("D://Articles//filehandling//filewritecharcters.txt");
            fw = new FileWriter("D://Articles//filehandling//newfile.txt");
            while((i=fr.read())!=-1)
            {
                fw.write((char)i);
                       
            }
            fr.close();
            fw.close();
           
            System.out.print("sucess");
           
        }catch(Exception e){System.out.println(e);}
    }
   

}