Monday 3 June 2013

Java File and IO : DataOutputStream

There are a lot of APIs regarding files and IO in Java. Some of the basics will be discussed here.
  1. BufferedInputStream
  2. BufferedOutputStream
  3. DataInputStream
  4. DataOutputStream
First let us differentiate all these.

1. BufferedInputStream :  kind of inputStream that buffers the input data in order to optimize the speed access to the data.

2. BufferedOutputStream : kind of outputStream that buffers bytes.

3. DataInputStream : is a kind of InputStream used to read data as primitive data types from an underlying input stream.

4.DataOutputStream : kinf of outputStream that allows user to write data as primitive data types.

Examples:

Using DataOutputStream in writing boolean data type

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

public class DataOutputStreamWriteBoolean {
   public static void main(String[] args) {
      String file = "C://tutorialpointph//booleanfile.txt";    
      try
      {
  //create the file booleanfile
  FileOutputStream fos = new FileOutputStream(file);
      
  /*    
  * DataOutputStream(OutputStream os) constructor.   
  */
      
  DataOutputStream dos = new DataOutputStream(fos);      
  boolean b = true; //One byte of data
      
  /*
  * writeBoolean() methods writes the boolean to output 
  * as a byte if true. If false, no byte is present.
  */
        
   dos.writeBoolean(b);
       
   System.out.println("boolean byte has been written.");
   dos.close();
        
      }  
      catch (IOException e)
      {
   System.out.println("IOException : " + e);
      }
   }
}

Using DataOutputStream in writing byte data type

Java File and IO: DataInputStream

There are a lot of APIs regarding files and IO in Java. Some of the basics will be discussed here.
  1. BufferedInputStream
  2. BufferedOutputStream
  3. DataInputStream
  4. DataOutputStream
First let us differentiate all these.

1. BufferedInputStream :  kind of inputStream that buffers the input data in order to optimize the speed access to the data.

2. BufferedOutputStream : kind of outputStream that buffers bytes.

3. DataInputStream : is a kind of InputStream used to read data as primitive data types from an underlying input stream.

4.DataOutputStream : kinf of outputStream that allows user to write data as primitive data types.

Examples:

Using DataInputStream in reading boolean data type

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class DataInputStreamReadBoolean {
 public static void main(String[] args){

 String file = "C://tutorialpointph//booleanfile.txt";    
     try
     {
       //Get the file to read using BufferedInputStream
       FileInputStream fin = new FileInputStream(file);
      
       /*
        * DataInputStream(InputStream in) constructor.
        */      
        DataInputStream din = new DataInputStream(fin);
      
        /*
         * readBoolean() method reads a byte from the file
         * and return true if the byte is not zero and 
         * false if byte is zero.     
         */
        
         boolean b = din.readBoolean();        
         System.out.println("Value on text file : " + b);        
   
         din.close();
        
     }
     catch(FileNotFoundException e)
     {
       System.out.println("File not found on path : " + e);
     }
     catch(IOException ie)
     {
       System.out.println("Exception while reading : " + ie);
     }
 }
}


Using DataInputStream in reading byte data type

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class DataInputStreamReadByte {
 public static void main(String[] args){
  String file = "C://tutorialpointph//bytefile.txt";    
     try
     {
       //Get the file to read using BufferedInputStream
       FileInputStream fin = new FileInputStream(file);
      
      /*
       * DataInputStream(InputStream in) constructor.
        */      
        DataInputStream din = new DataInputStream(fin);
      
        /*
         * readByte() method reads a byte from the file         
         */
        
         byte b = din.readByte();        
         System.out.println("Value on text file : " + b);        
   
         din.close();
        
     }
     catch(FileNotFoundException e)
     {
       System.out.println("File not found on path : " + e);
     }
     catch(IOException ie)
     {
       System.out.println("Exception while reading : " + ie);
     }
 }
}

Using DataInputStream in reading int data type

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class DataInputStreamReadInt {
 public static void main(String[] args){
  String file = "C://tutorialpointph//intfile.txt";    
     try
     {
       //Get the file to read using BufferedInputStream
       FileInputStream fin = new FileInputStream(file);
      
       /*
        * DataInputStream(InputStream in) constructor.
        */      
        DataInputStream din = new DataInputStream(fin);
      
        /*
         * readInt() method reads an integer primitive
                * from the file         
         */
        
         int i = din.readInt();        
         System.out.println("Value on text file : " + i);        
   
         din.close();
        
     }
     catch(FileNotFoundException e)
     {
       System.out.println("File not found on path : " + e);
     }
     catch(IOException ie)
     {
       System.out.println("Exception while reading : " + ie);
     }
 }
}

Java File and IO: BufferedOutputStream

There are a lot of APIs regarding files and IO in Java. Some of the basics will be discussed here.

  1. BufferedInputStream
  2. BufferedOutputStream
  3. DataInputStream
  4. DataOutputStream
First let us differentiate all these.

1. BufferedInputStream :  kind of inputStream that buffers the input data in order to optimize the speed access to the data.

2. BufferedOutputStream : kind of outputStream that buffers bytes.

3. DataInputStream : is a kind of InputStream used to read data as primitive data types from an underlying input stream.

4.DataOutputStream : kinf of outputStream that allows user to write data as primitive data types.

Examples:

BufferedOutputStream

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

public class BufferedOutputStreamExample {
 public static void main(String[] args) {
  String file = "C://tutorialpointph//file.txt";
  BufferedOutputStream bos = null;
         
        try
        {
            //Get the file to write data to 
            FileOutputStream fos = new FileOutputStream(file);
                 
            /*
             * creates a BufferedOutputStream          
             */  
            bos = new BufferedOutputStream(fos);
                 
            char a = 'a';  
            bos.write(a);
            System.out.println("Char 'a' has been written.");
         }
         catch(FileNotFoundException e){
             System.out.println("File not found on path" + e);
         }
         catch(IOException ie){
             System.out.println("Exception while writing" + ie);
          }
         finally
         {
              try
              {
                 if(bos != null)
                 {
                    bos.flush();
                    bos.close();
                 }
               }
               catch(Exception e){}
         }
 }
}

Java File and IO: BufferedInputStream

There are a lot of APIs regarding files and IO in Java. Some of the basics will be discussed here.

  1. BufferedInputStream
  2. BufferedOutputStream
  3. DataInputStream
  4. DataOutputStream
First let us differentiate all these.

1. BufferedInputStream :  kind of inputStream that buffers the input data in order to optimize the speed access to the data.

2. BufferedOutputStream : kind of outputStream that buffers bytes.

3. DataInputStream : is a kind of InputStream used to read data as primitive data types from an underlying input stream.

4.DataOutputStream : kinf of outputStream that allows user to write data as primitive data types.

Examples:

BufferedInputStream

/*
* Example of Buffered Input Stream
*/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class BufferedInputStreamExample {
 public static void main(String[] args) {
           
  //Get the file to read using BufferedInputStream
        File file = new File("C://tutorialpointph//file.txt");
        BufferedInputStream bin = null;
         
        try
        {
            //obtains input bytes from the file
            FileInputStream fin = new FileInputStream(file);                  
            /*
            * creates a BufferedInputStream and saves 
            * it into the buffer array for further use
            */                  
            bin = new BufferedInputStream(fin);                                      
            //read the file 
            //available : while there are bytes to read
            while( bin.available() > 0 ){                        
             System.out.print((char)bin.read());
            }                  
         }
         catch(FileNotFoundException e){
            System.out.println("File not found on path" + e);
         }
         catch(IOException ie)
         {
            System.out.println("Exception while reading " + ie); 
           }
         finally
         {
            //close the BufferedInputStream after reading
            try{
              if(bin != null)
              bin.close();                                  
             }catch(IOException ie){
              System.out.println("Error while closing : " + ie);
             }                  
         }
   }
}

Friday 19 April 2013

Parsing XML with JQuery

To parse an XML file with JQuery, you can follow these simple steps.

1. Obtain the xml using JQuery Ajax. There are two possible location where the xml file can be located. You have to make sure of your file path.
2. Parse the Ajax Response (your XML file) and append the data to your html code.

Suppose you have a XML file: (download here)

<student_list>
   <students>
     <student_id>2013001</student_id>
       <name>Clare Marie Ciriaco</name>
    </students>
    <students>
      <student_id>2013002</student_id>
        <name>Jane Doe</name>
   </students>
   <students>
     <student_id>2013003</student_id>
       <name>John Fitzgerald</name>
   </students>
</student_list>

To parse it,


OUTPUT:




Friday 12 April 2013

java.lang.ClassNotFoundException: com.sun.el.ExpressionFactoryImpl

When running JSF with Tomcat 7.0, I stumbled upon this error. Turns out, you  have to put the following JARS in Tomcat's library folder before running your project.

My Path: C:\Program Files\apache-tomcat-7.0.23\apache-tomcat-7.0.23\lib
Note: This may vary from different users
  • el-api-2.2.jar
  • el-impl-2.2.jar

Wednesday 20 March 2013

Understanding Object-Relational Mapping

Object-Relational Mapping, or in short ORM is used to map data taken from a database to Objects.

For instance, you have a table PERSON in your database with the following values:






In your code, you need to get the Person object with id=2. So the expected output should be

{ 2, Jane, Fitzgerald, jfitzgerald@gmail.com }


So you create a query,

Select * from Person where id='2'. This is where hibernate, iBatis or other ORM.













The blue line is the job for iBatis, Hibernate and other ORM. Every ORM has a different way of mapping the data from the database to an object.



Thursday 10 January 2013

Java: String Concatention Precedence

With the ability of Java to concatenate strings using the plus (+) sign, a common mistake that new programmers may face is the mix up of adding integers and strings. Let me show you a sample.

Consider the following code:

public class StringConcatTest { 
   public static void main(String[] args){
       int firstNum = 10;
       int secNum = 5;    
       System.out.println(firstNum + secNum + " total number of apples.");
       System.out.println("Total number of apples: " + firstNum + secNum);       
   }
} 

OUTPUT:
15 total number of apples.
Total number of apples: 105 


Clearly, the second sentence is incorrect.

Tuesday 1 January 2013

Java: Valid Java Keywords

A table of java keywords that cannot be used as identifiers.


Java: Handling Braces

It is good programming practice to maintain a format when coding. These formats can be anything from indentation, white spaces, line wrapping, separation of code and braces handling. Why is it important? - To make the code readable.

There are two distinct way of handling braces:

1. K&R style

while(a!=b){
     doMethod();
}

2. Allman Style

while(a!=b)
{
     doMethod();
}

Personally I prefer the K&R and I practice it on my code. Always remember, good coding practice makes a good programmer. :)