Sunday, 27 March 2016

Java NIO - Part 2


Operations on File using Java NIO: Java NIO provides easy mechanism for File copying, moving and deleting. Let's try it out with a basic java program:



package com.bpjoshi.javapriest.iotutorials.nio2;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author Bhagwati Prasad (Joshi)
 */
/*
 * Operations On File- Copy, Move and Delete
 *1: Copying Content of a file in another file.
 *2. Deleting a File
 *3. Moving a File
 */
public class JavaNIO3 {
 public static void main(String[] args) throws IOException {
  //1:
  Path source=Paths.get("H:", "Tutorials", "JavaNio", "nio.txt");
  Path target=Paths.get("H:", "Tutorials", "JavaIO", "abcd.txt");
  try{
  Files.copy(source, target);
  }catch(Exception ex){
   ex.printStackTrace();
  }
  
  //2:
  Files.delete(target);
  
  //3:
  Files.move(source, target);
  
 }
 
}



In the code above , if you copy another file from another source to target file, it gives FileAlreadyExistsException. To deal with this, java provides an optional third parameter while copying. For example
Files.copy(source2, target, StandardCopyOption.REPLACE_EXISTING);


This will replace this replace the existing file.  What happens when you try to delete a file that 
doesn't exist. It will throw NoSuchFileException. But java is very careful, it also provides you 
with another method which is Files.deleteIfExists(path). It returns false, if the file doesn't
exist.



Object Oriented Programming Concepts


Saturday, 26 March 2016

Factory Design Pattern

Factory Design Pattern is probably the most used design pattern in Java programming. It is a Creational Design Pattern like Singleton and hence used for creating objects.

To be continued...

Java NIO (NIO.2 Added to Java SE 7)


In Java 7, there are two important packages added for IO related operations. 

1) java.io.file
2) java.nio.file.attribute

java.nio.file : Let's have a look at classes and interfaces of this package first.


Path: This is an interface which represents a file or directory. It is similar to File class of java.io in this regard however it is quite a lot more powerful than a File.


Paths: This class has static methods for creating Path objects. It acts like a factory of object


Files: It has some static methods that work with path objects.


Similar to File, java.nio.Path represents only a location in the machine. You have to create a fille by using Files.createFile(Path target). 


We create a file using static method of File class which is : Files.createFiles(path);

Important Steps:

1. Path p1=Paths.get("H:\\Tutorials\\JavaNio");

      Path object can be created by calling static method get() of Paths Class
      Remember Path is an interface while Paths is a class

2.  We can also create Path object as : 
     
        Path p2
=Paths.get("H:", "Tutorials", "JavaNio");
        
Path p3= Paths.get("H:\\Tutorials", "JavaNio");

3. To create a file for a FTP path:


        Path ftpPath= Paths.get(URI.create("file:///H:/Tutorial/Tutorials"));

        Path ftpPath= Paths.get("file:///H:/Tutorial/Tutorials");

        If you use the code just agove for FTP protocol path, this will throw an Exception
        java.nio.file.InvalidPathException

4. How the Paths.get actually works, although you don't need to write that in your program.

        Path actualPath=FilesSystems.getDefault().getPath("H:", "Tutorials", "JavaNio");

5. File and Path can be converted to each other, hence you can use IO and NIO together.

        File file= new File("abc.txt");
    Path convertedToPath=file.toPath();
    Path path= Paths.get("H:\\abc.txt");
    File convertedToFile=path.toFile();

T0 Creating Files And Directories in NIO:



package com.bpjoshi.javapriest.iotutorials.nio2;

import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author Bhagwati Prasad (Joshi)
 */
/*
 * Creating Files and Directories
 * 1: Creating Files , example nio.txt
 * 2: Creating Directories
 * creating a directory under JavaNio eg /books/java
 */
public class JavaNIO2 {
 public static void main(String[] args) {
  //1:
  Path path= Paths.get("H:", "Tutorials", "JavaNio", "nio.txt");
  System.out.println(Files.exists(path)); //Prints false
  try {
   Files.createFile(path);
  } catch (IOException e) {
   e.printStackTrace();
  }
  System.out.println(Files.exists(path));
  
  //2:
  Path path2=Paths.get("H://Tutorials/JavaNio/books/javabooks");
  Path file=Paths.get("H://Tutorials/JavaNio/books/javabooks/java.pdf");
  
  try {
   Files.createDirectories(path2);
   Files.createFile(file);
   //Create file in newly created Directory
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}



That's it for this tutorial. Please visit Java NIO - Part 2 for the next part of Java NIO Tutorial.

Happy Coding!

Friday, 25 March 2016

Java IO - Part 1



Introduction:  IO has been a part of Java since the very beginning beginning. In Java 1.4 NIO i.e. new input output was added for increasing input/output performance and making it easier to use.

NIO.2 was added to Java SE 7, which uses very powerful I/O techniques which can handle huge data for I/O operations and give a good performance
.

There can be many different types of I/O operations e.g. File I/O, Console I/O, thread I/O, High Performance I/O, Byte Oriented I/O, Character Oriented I/O, I/O Filtering, Wrapping, Serialization.

We will cover Basic File IO in this post. We will use Readers and Writer classes because we will be reading and writing characters. We will read and write bytes with use of Stream classes in the upcoming tutorials. Below are some important classes that we need to know before we begin with hands on practice:



1. File: This class is used for making new empty files, directories, searching for files etc.


2. FileReader:  It is used to read character files. Its read() method method allows you read single character or a fixed bunch of characters. FileReader is a low level class and usually wrapped by higher level classes like BufferedReader.

3. BufferedReader: It is used to improve performance of lower level reader classes like FileReader and make them easier to use. BufferedReader can handle large chunks of data. It makes use of buffering technique where data is stored in buffer and thus increasing performance.

4. FileWriter: Like FileReader, FileWriter is also a lower level class. Its write() methods allows write characters or strings to a file. FileWriters are wrapped by higher level writers like BufferedWriters or PrintWriters

5. BufferedWriter: This class is used to make lower level writer classes like FileWriter efficient and easier for use. Like BufferedReader, they also handle large chunk of data and create a buffer of data.

6. PrintWriter: This class is provides some of powerful methods for formatting data and reading from and writing to files. After Java 5 changes, you can build PrintWriters with files and string as well. There are some new methods like format(), printf() and append() making it very flexible.

7. Console: Added in java 6, this class provides methods to read input from the console and write output to console (which can also be formatted by this class).


Creating Files Using the File Class:


The java File class object represents an actual file or directory on your machine. IO operations are risky and involve checked exceptions to so will put IO related code inside try block and catch IOException. Let's create a file:



package com.bpjoshi.javapriest.iotutorials;

import java.io.File;
import java.io.IOException;

/**
 * @author Bhagwati Prasad (Joshi)
 * */
class WriteAFile {
    public static void main(String[] args) {
        try {
  File file = new File("firstFile.txt");
  // you didn't create a file yet
  // you just created a filename
  System.out.println(file.exists());
  // exists() method of file class
  // The code above will print false
  file.createNewFile();
  // createNewFile() method to create file
  System.out.println(file.exists());
  // This will now print true
 } catch (IOException ex) {
  System.out.println(ex);
 }
    }
}





FileWriter and FileReader:  Using FileWriter to write to a file and FileReader to read from the file.(Note: FileReaders and FileWriters are used with  Buffered Readers and Writers mostly)



package com.bpjoshi.javapriest.iotutorials;

import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author Bhagwati Prasad (Joshi)
 * */
class ReaderWriterFile {
    public static void main(String[] args) {
        try {
  File file = new File("firstFile.txt");
  FileWriter fw = new FileWriter(file);
  // Code above creates a file
  fw.write("Hello World"); // Write Hello World to file
  fw.flush(); // flush the data to file before closing
  fw.close(); // closing the file after writing
  FileReader fr = new FileReader(file); // FileReader object
  char[] chArr = new char[20];
  // character array that stores file content
  fr.read(chArr); // read the whole file & put content in chArr
  for (char ch : chArr) { // looping through file content array
   System.out.print(ch);
  }
  fr.close(); // finally close the reader
 } catch (IOException ex) {
  System.out.println(ex);
 }
    }
}



Explanation:  The program above creates a FileWriter object which is referenced by FileWriter type reference variable fw. At the same time, an empty text file is created in the current directory. We write a string to the file and we flush the data. Flush is used, because some of the data is present in buffers. If you do many write operations and at the end you call flush(), it makes sure the last bits of your data have also been stored in the file. The file is closed at the end of read and write operations, because otherwise program will not free this file resource otherwise.


We would like to use a smarter way of writing to and reading from a file which is able to write and read huge amount of data. We will have to use higher level classes for that purpose. One thing is sure, we will always use File type of object for our file, hence these higher level classes, if accept File as a constructor, it will be really good.

Checkout PrintWriter class, it has a constructor that accepts File object. Looking at it's methods, it provides a number of methods to write to a file. For example methods like print(), println(), write(), flush() and close() etc. 

We can safely write:




package com.bpjoshi.javapriest.iotutorials;

import java.io.File;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author Bhagwati Prasad (Joshi)
 * */
class HighLevelFileOperation{ public static void main(String[] args){ try{ File file= new File("myFile.txt"); //Declare a file PrintWriter pw = new PrintWriter(file); //Creates a PrintWriter object and a file in directory pw.println("Hello there!"); pw.println("I am studying IO."); //This writes the data to File pw.flush(); pw.close(); //Flush and close PrintWriter FileReader fr= new FileReader(file); //Load the file using FileReader BufferedReader br = new BufferedReader(fr); //Create a high level Reader, i.e. BufferedReader String line= br.readLine(); //Read first line from the file System.out.println(line); //It will print first line of the file(i.e. Hello there! br.close();//close the BufferedReader } catch(IOException ex){ System.out.println(ex); } } }



Explaination: BufferedReader accepts FileReader object in its constructor which accepts a File ojbect in its constructor. Low level operation objects are chained inside High level operation objects.


Playing in deep with Files and Directories:

1. File class is use to create file, delete file, rename file, check whether file exists, create directory etc.
2. File file= new File("myFile.txt") It doesn't create any file, but if a file with name myFile.txt already exists a reference to that existing file is returned.

3.  To create an actual file on disk, either call file.createNewFile() or make a                 PrintWriter/BufferedWriter Object.

4. Creating a Directory using File class: 

File myDir= new File("myDir");
myDir.mkdir();

5. You can create file in the newly create directory myDir:

File file= new File(myDir, "myFile.txt");
myFile.createNewFile();

6. Now you can write to this file in myDir directory using PrintWriter:
PrintWriter pw = new PrintWriter(file);
pw.println("Hello Java World");
pw.flush();
pw.close();

7. You have to make directory yourself, there is no way, PrintWriter or other high level Writer classes will create directory for you unlike file which is can be created by these. Be Aware! This will generate java.io.IOException: No such file or directory

8. Your file object can have reference to an existing directory. Now how to check, if it's a directory: boolean b=myDir.isDirectory()

Let's apply the skills learnt so far to create the program below: FileAndDirectory.java




package com.bpjoshi.javapriest.iotutorials;

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Bhagwati Prasad (Joshi)
 * */
public class FileAndDirectory {
 public static void main(String[] args) {
  try {
   // Make a directory on path H:\Tutorials
   File ioDir = new File("H:\\Tutorials\\IODirectory");
   ioDir.mkdir();
   // Add a file to directory
   File file = new File(ioDir, "myProfile.txt");
   // Create an actual file on the directory
   file.createNewFile();
   
   //Add content to the File using PrintWriter
   PrintWriter pw= new PrintWriter(file);
   pw.println("I am a java tutor.");
   pw.println("I am a java developer as well.");
   pw.flush();
   pw.close();
   
   //Read from the  File
   FileReader fr= new FileReader(file);
   BufferedReader br= new BufferedReader(fr);
   String str;
   while(((str=br.readLine())!=null)){
    System.out.println(str);
   }
   //When there is no more data, br.readLine() returns null
   br.close();   //Close the BufferedReader
   
   //Create and Delete Another File in the directory
   File file1=new File(ioDir, "yourProfile.txt");
   file1.createNewFile();
   file1.delete(); //This will delete the newly created file
   
   //To rename this file create a new File reference
   File newFile= new File(ioDir, "abcd.txt");
   file.renameTo(newFile); //Wil change name to abcd.txt
   
   //Search files in the directory
   //Let's create a directory H:\Tutorials\IODirectory\IOSearch
   //Create 4-5 Text files in the directory to be searched
   //String array files will hold names of Files
   String[] files= new String[100];
   //Directory
   File search=new File("H:\\Tutorials\\IODirectory\\IOSearch");
   //List  all files in directory
   files=search.list();
   //Printing names from directory
   for(String fileName: files){
    System.out.println("Files found "+fileName);
   }
  } catch (IOException ex) {
   ex.printStackTrace();
  }
 }

}



Java.io.Console class is used for reading input and showing output to console elements i.e. keyboad and monitor screen. It has two important methods, a) readLine() which reads in form of string and b) readPassword() method which returns an character array.

Passwords are stored in character array because once you are done with the array object you can nullify it while string will be present somewhere in the string constant pool, which is a security risk.

That's it for this tutorial, in case of any queries or suggestions, feel free to comment.

Happy Coding!

Sunday, 13 March 2016

Singleton Design Pattern in Java

Singleton pattern ensures that only one instance of the class exists at a time in the whole JVM.

Use of Singleton Class:

Logger classes: Without creating a new object each time a logging operation is performed, we use a singleton of Logger classes


Servlets: Servlets are also based on singleton pattern, which however can be easily broken by defining servlet entry by another name in web.xml. Generally servlets are singletons. They are initialized at the beginning and later on only their service methods get called (i.e. doGet, doPost)

Configuration Classes: For example DB configuration class, generally is a singleton.

Let's move on to create our first singleton class Employee.


1. Make constructor of Employee class private so that no other class can create its object.
2. Create an instance variable of Employee type which refer the singleton Employee object
3.  Create a public static method that returns instance of Employee class.

Eager Loading way: Create Employee Singleton class using Eager loading i.e. object of Employee class is created when the class is loaded in JVM. 


package com.bpjoshi.singleton;   
  public class Employee {  
   //Make an Instance of Singleton class  
   private static final Employee instance = new Employee();   
   //make its constructor private  
   private Employee(){}   
   //Make a getInstance() method to retrieve the singleton  
   public static Employee getInstance(){   
      return instance;   
    }   
  }   

Singleton is used mostly with File Systems, Database Connections, Management Tools. They are using lots of important resources. Hence we should create its object only when it's needed.

Lazy Loading way: In this approach, singleton object is created when it's first time requested.


 package com.bpjoshi.singleton;  
 public class Employee {
   //Declare Instance of Singleton class
   private static final Employee instance;  
   //make its constructor private
   private Employee(){} 
   //Make a getInstance() method to retrieve the singleton
   public static Employee getInstance(){
     if(instance==null){
        instance= new Employee();
     }
     return instance;  
   }  
 } 


The above implementation works fine in a single threaded environment, however it will be easily destroyed in a multi threaded environment. If two or more threads access this resource simultaneously, they might get different object.

Thread Safe Singleton: You can easily make this singleton thread safe by making getInstance() Method synchronized.


 package com.bpjoshi.singleton;  
 public class Employee {
   //Declare Instance of Singleton class
   private static final Employee instance;  
   //make its constructor private
   private Employee(){} 
   //Make a getInstance() method to retrieve the singleton
   public static synchronized Employee getInstance(){
     if(instance==null){
        instance= new Employee();
     }
     return instance;  
   }  
 } 

Although the above implementation provides thread safety, yet it makes the program slower due to it being synchronized.

Bill Pugh Singleton: To overcome this issue of synchronization, Bill Pugh came up with his implementation using static inner helper class. Static inner class is not loaded into memory until its getInstance() method is not called.


 package com.bpjoshi.singleton;  
 public class Employee {
 //private constructor of employee
 private Employee(){}
 //private static inner helper class
 private static class EmployeeHelper{
    private static final Employee instance
      =new Employee();
 }
 //public method to get singleton object
 public static Employee getInstance(){
    return EmployeeHelper.instance;
   }
 } 

Bill Pugh Singleton is the best approach so far, however it can be easily destroyed with use of java reflection.

Breaking Bill Pugh Singleton with java Reflection:



package com.bpjoshi.singleton;
import java.lang.reflect.*;

public class EmployeeReflection {

    public static void main(String[] args) {
        Employee instance1 = Employee.getInstance();
        Employee instance2 = null;
        try {
            Constructor[] cstr 
             = Employee.class.getDeclaredConstructors();
            for (Constructor constructor : cstr) {
               //Setting constructor accessible
                constructor.setAccessible(true);
                instance2 
                   = (Employee) constructor.newInstance();
                break;
            }
        } catch (Exception e) {
             System.out.println(e);
        }
        System.out.println(instance1);
        System.out.println(instance2);
    }
}


Enum Singleton: We can use Enum to create singleton in java to come over the reflection. However the obvious drawback is we cannot have lazy loading in Enum.

public enum Employee{
    INSTANCE;
}

It's instance can be gotten by referring Employee.INSTANCE

Breaking Enum Singleton with Serialization:  If the Singleton class implements java.io.Serializable and a singleton object is serialized and then deserialized more than once, there will be many instances of Singleton.

In order to avoid serialization issue, implement readResolve() method in your Singleton class as below:

public class Employee implements Serializable {
   //some code here
  //call this method immediately after De-serialization
  //it returns an instance of singleton
  protected Object readResolve() {
   return getInstance();
   }
 }


That's it for this tutorial. If any queries or suggestions, please feel free to write in comments.

Happy Coding!