Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

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

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. :)

Thursday, 18 October 2012

Java : Date Formats

Common Questions with Date Format

1. What are the possbile date formats?
2. Can I use any delimiter?

I couldn't find a concrete explanation of the possible date formats but I decided to write one based on trial and and error.

Date dateNow = new Date();

a.
System.out.println(dateNow);
Output: Fri Oct 19 09:26:59 CST 2012

b.
String dateStr = new SimpleDateFormat("MMM/dd/yyyy").format(dateNow);
System.out.println(dateStr);
Output: Oct/19/2012

Use MMM to get Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec

Note: If the output month is not in the format "Oct", you can try adding Locale.ENGLISH:
String df = new SimpleDateFormat("MMM/dd/yyyy", Locale.ENGLISH).format(dateNow);

c.
String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(dateNow);
System.out.println(dateStr);
Output: 2012-10-19 

d.
String dateStr  = new SimpleDateFormat("yyyy/mm/dd").format(dateNow);
System.out.println(dateStr);
Output: 2012/38/19

Note : In letter D, the output is supposedly 2012/10/19. However, you are using the format "yyyy/mm/dd". The month variable should be in capitals, MM instead of mm.
Note : Also make sure that your year variable are in small letters, yyyy instead of YYYY. It will return an error.

As you can see, the format can be interchangeable.

2. Can I use any delimiter? Yes.