BEING JAVA GUYS


Sunday, 16 February 2014

In our previous discussions we came across a quick introduction to Java’s Collection API and Implementation classes for List, Set and Map interface. In this particular blog we will discuss about a very useful topic i.e. "Why to override equals() in Java" and "How to override equals in Java".

We all know it very well that all classes in Java are descendent of Object class, or we can say every class inherits the methods and properties of Object class by default. There are a number of methods in Object class and hence is "public boolean equals(){}".

The public boolean equals(){}, compares two objects and return true or false accordingly. If we don’t override equals in our own class than one present in Object class is called and it compares the object using ‘==’ operator and hence two objects are equal only if their references are same.

Assume we have an class Apple, lets compare its objects using equals() and examine the result.
class Apple {

 private int id;
 private String name;

 public Apple() {
 }

 public Apple(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}


No lets see what happened when we call an equals() method from Object class itself without overriding it.
public class Implementation {
 public static void main(String args[]) {
  Apple greenApple = new Apple(1, "Apple");
  Apple redApple = new Apple(1, "Apple");

  // returns a false
  System.out.println(greenApple.equals(redApple));
 }
}


In the example above we can see that even if two instance of Apple are having same data in them but the equals() method from Object class is assuming them to be non equal. The reason is the default implementation of equals() check for references and two objects are same only if their reference is same. And certainly you would not want this kind of behavior in your application, hence we override equals.

Note: Two String object with same values returns true on equals() even if having different references, the reason is String itself override equals() and implement the functionally so that the String content to compare not their references. Hence we can do it in our very own class.


We can override equals() in our own class and give that our own implementation to compare objects considering some contract. The meaning of contract here is that when overriding equals() we must took care of certain rules and those rules should not violate.

If an class “Apple” has three instances “greenApple” , “redApple” and “yellowApple” than according to contract

1) greenApple.equals(greenApple) must be true always. Reflexive

2) If greenApple.equals(redApple) is true than redApple.equals(greenApple) must be true. Symmetric

3) If greenApple.equals(redApple) is true and redApple.equals(yellowApple) is also true than greenApple.equals(yellowApple) must be true. Transitive

4) For any two refrences say “redApple” and “yellowApple” the equals() method must return true or false consistently unill and unless the property of class that is used is equals() is not modified. Consistent

5) For any non-null reference value greenApple, greenApple.equals(null) should return false. Null Test



Lets now look at our modified version of Apple with an override equals() method.
class Apple {

 private int id;
 private String name;

 public Apple() {
 }

 public Apple(int id, String name) {
  this.id = id;
  this.name = name;
 }

 /*
  * One can use his own logic here unless the contract is being followed.
  */
 public boolean equals(Object o) {
  if (o instanceof Apple && ((Apple) o).getName() == name
    && ((Apple) o).getId() == id)
   return true;
  else
   return false;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}


Now let’s check if we did it right and does not violate the contract.
public class Implementation {
 public static void main(String args[]) {
  Apple greenApple = new Apple(1, "Apple");
  Apple redApple = new Apple(1, "Apple");
  Apple yellowApple = new Apple(1, "Apple");

  // Reflexive Test : true
  System.out.println("Reflexive Test : " + greenApple.equals(greenApple));

  // Symmetric Test : true
  if (greenApple.equals(redApple)) {
   System.out.println("Symmetric Test : "
     + redApple.equals(greenApple));
  }

  // Transitive Test : true
  if (greenApple.equals(redApple) && redApple.equals(yellowApple)) {
   System.out.println("Transitive Test : "
     + yellowApple.equals(greenApple));
  }

  // Null Test : false
  if (greenApple != null) {
   System.out.println("Null Test : " + greenApple.equals(null));

  }
 }
}


And we are getting the expected result that passes the equals() override contract. Now the conclusion of the whole story is that:

1) The public boolean equals(){} is a method that resides in Object class and hence can be overridden in our own classes as well.

2) If one does not override it than the default behavior is being calles i.e. two objects are equal only if their references are same.

3) We can override equals() in our own class and can give own implementation to compare two objects until and unless we are not violating the equals() contract.

Big Big NOTE: If you override equals() in your own class than you must override hashCode() as well, unless it can violate hashCode() contract with equals() that results in Hash Based collections functionality and implementation.


In this particular blog we came across "why to override equals() in Java" and "How to override equals in Java". In our upcoming blog we will come across "how to override hashCode() in Java" and other tips and tricks about Java.








Thanks for reading !
Being Java Guys Team


Friday, 13 December 2013

In today's discussion we will came across 'How to Create and Delete a folder on FTP Server in Java'. We are using 'apache commons-net' API that holds all necessary classes to deal with FTP operations like, create connection , get list of all files on ftp , upload file to ftp , download files from ftp , create and delete a directory on ftp and delete a file on ftp.

In this particular blog we will see an example of How to Create and Delete a folder on FTP Server in Java, all steps included in the process are:

1)  Get a 'FtpClient' object from 'org.apache.commons.net.ftp.FTPClient' Class.
2)  Use 'connect()'  method of API to open a connection to the FTP Server, pass ftp path or url as           parameter to connect() method.
3)  Call login() method of API on ftpClient, and pass server credentials as parameter. It returns 'true' if login is successful and false otherwise.
4)  Call makeDirectory(String pathname) method of API on ftpClient to make a directory on the FTP server. It returns 'true' if deletion is successful and false otherwise.
5)  Call removeDirectory(String pathname) method of API on ftpClient to delete a directory on the FTP server. It returns 'true' if deletion is successful and false otherwise.
6)  Call logout() method of API on ftpClient to logout from connected ftp server. It returns 'true' if logout is successful and false otherwise.
7)  Call disconnect() method of API on ftpClient to end connection from connected ftp server. It returns 'true' if disconnect is successful and false otherwise.


Required Libraries to add


To use implementation of 'Commons Net' we need to add following dependency to our pom.xml. Here 'commons-net' is required dependency but 'commons-io' is optional. 'commons-io' provides a number of general purpose implementation to deal with IO.
 <dependencies>
  <dependency>
   <groupId>commons-net</groupId>
   <artifactId>commons-net</artifactId>
   <version>2.0</version>
  </dependency>
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
  </dependency>

 </dependencies>


Create and Delete a folder on FTP Server in Java - Example Code


package com.beingjavaguys.testftp;

import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;

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

  // get an ftpClient object
  FTPClient ftpClient = new FTPClient();

  try {
   // pass directory path on server to connect
   ftpClient.connect("nagesh12.5gbfree.com");

   // pass username and password, returned true if authentication is
   // successful
   boolean login = ftpClient.login("username", "password");

   if (login) {
    System.out.println("Connection established...");

    boolean folderCreated = ftpClient.makeDirectory("feeds");

    if (folderCreated) {
     System.out.println("Directory created successfully !");
    } else {
     System.out.println("Error in creating directory !");
    }

    boolean folderdeleted = ftpClient.removeDirectory("feeds");

    if (folderdeleted) {
     System.out.println("Directory removed successfully !");
    } else {
     System.out.println("Error in removing directory !");
    }
    // logout the user, returned true if logout successfully
    boolean logout = ftpClient.logout();
    if (logout) {
     System.out.println("Connection close...");
    }
   } else {
    System.out.println("Connection fail...");
   }

  } catch (SocketException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    ftpClient.disconnect();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}


Output : Here is expected output, connection started, creating and deleting directory on ftp server and connection ends.



Here we are done with 'Create and Delete a folder on FTP Server in Java - Using Commons Net API'. In our upcoming blogs we will see more about Java Programming and other opensource technologies.








Thanks for reading !
Being Java Guys Team


In today's discussion we will came across 'How to Delete files from FTP Server in Java'. We are using 'apache commons-net' API that holds all necessary classes to deal with FTP operations like, create connection , get list of all files on ftp , upload file to ftp , download files from ftp , create and delete a directory on ftp and delete a file on ftp.

In this particular blog we will see an example of How to Delete files from FTP Server in Java, all steps included in the process are:

1)  Get a 'FtpClient' object from 'org.apache.commons.net.ftp.FTPClient' Class.
2)  Use 'connect()'  method of API to open a connection to the FTP Server, pass ftp path or url as           parameter to connect() method.
3)  Call login() method of API on ftpClient, and pass server credentials as parameter. It returns 'true' if login is successful and false otherwise.
4)  Call deleteFile(String pathname) method of API on ftpClient to delete a file on the FTP server. It returns 'true' if deletion is successful and false otherwise.

5)  Call logout() method of API on ftpClient to logout from connected ftp server. It returns 'true' if logout is successful and false otherwise.
6)  Call disconnect() method of API on ftpClient to end connection from connected ftp server. It returns 'true' if disconnect is successful and false otherwise.


Required Libraries to add


To use implementation of 'Commons Net' we need to add following dependency to our pom.xml. Here 'commons-net' is required dependency but 'commons-io' is optional. 'commons-io' provides a number of general purpose implementation to deal with IO.
 <dependencies>
  <dependency>
   <groupId>commons-net</groupId>
   <artifactId>commons-net</artifactId>
   <version>2.0</version>
  </dependency>
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
  </dependency>

 </dependencies>


Delete files from FTP Server in Java - Example Code


package com.beingjavaguys.testftp;

import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;

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

  // get an ftpClient object
  FTPClient ftpClient = new FTPClient();

  try {
   // pass directory path on server to connect
   ftpClient.connect("nagesh12.5gbfree.com");

   // pass username and password, returned true if authentication is
   // successful
   boolean login = ftpClient.login("username", "password");

   if (login) {
    System.out.println("Connection established...");

    boolean delete = ftpClient.deleteFile("uploadedFile.txt");
    if (delete) {
     System.out.println("File deleted successfully !");
    } else {
     System.out.println("Error in deleting file !");
    }

    // logout the user, returned true if logout successfully
    boolean logout = ftpClient.logout();
    if (logout) {
     System.out.println("Connection close...");
    }
   } else {
    System.out.println("Connection fail...");
   }

  } catch (SocketException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    ftpClient.disconnect();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}


Output : Here is expected output, connection started, file deleted from server and connection ends.



Here we are done with 'Delete files from FTP Server in Java - Using Commons Net API'. In our upcoming blogs we will see more about Java Programming and other opensource technologies.








Thanks for reading !
Being Java Guys Team


Thursday, 12 December 2013

In today's discussion we will came across 'How to Download files from FTP Server in Java'. We are using 'apache commons-net' API that holds all necessary classes to deal with FTP operations like, create connection , get list of all files on ftp , upload file to ftp , download files from ftp , create and delete a directory on ftp and delete a file on ftp.

In this particular blog we will see an example of How to Download files from FTP Server in Java, all steps included in the process are:

1)  Get a 'FtpClient' object from 'org.apache.commons.net.ftp.FTPClient' Class.
2)  Use 'connect()'  method of API to open a connection to the FTP Server, pass ftp path or url as           parameter to connect() method.
3)  Call login() method of API on ftpClient, and pass server credentials as parameter. It returns 'true' if login is successful and false otherwise.
4)  Get FileOutputStream object to write to the file with specified file name.
5)  Call retrieveFile(String remote, OutputStream local) method of API on ftpClient, and pass desired downloadable file name(as on server) as first argument and pass output stream object as second argument.
6)  Call logout() method of API on ftpClient to logout from connected ftp server. It returns 'true' if logout is successful and false otherwise.
7)  Call disconnect() method of API on ftpClient to end connection from connected ftp server. It returns 'true' if disconnect is successful and false otherwise.


Required Libraries to add


To use implementation of 'Commons Net' we need to add following dependency to our pom.xml. Here 'commons-net' is required dependency but 'commons-io' is optional. 'commons-io' provides a number of general purpose implementation to deal with IO.
 <dependencies>
  <dependency>
   <groupId>commons-net</groupId>
   <artifactId>commons-net</artifactId>
   <version>2.0</version>
  </dependency>
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
  </dependency>

 </dependencies>


Download files from FTP Server in Java - Example Code


package com.beingjavaguys.testftp;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;

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

  // get an ftpClient object
  FTPClient ftpClient = new FTPClient();
  FileOutputStream fos = null;

  try {
   // pass directory path on server to connect
   ftpClient.connect("nagesh12.5gbfree.com");

   // pass username and password, returned true if authentication is
   // successful
   boolean login = ftpClient.login("username", "password");

   if (login) {
    System.out.println("Connection established...");

    fos = new FileOutputStream("files/downloadedFile.txt");
    boolean download = ftpClient.retrieveFile("uploadedFile.txt",
      fos);
    if (download) {
     System.out.println("File downloaded successfully !");
    } else {
     System.out.println("Error in downloading file !");
    }

    // logout the user, returned true if logout successfully
    boolean logout = ftpClient.logout();
    if (logout) {
     System.out.println("Connection close...");
    }
   } else {
    System.out.println("Connection fail...");
   }

  } catch (SocketException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    ftpClient.disconnect();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}


Output : Here is expected output, connection started, file downloaded from server and connection ends.



Here we are done with 'Download files from FTP Server in Java - Using Commons Net API'. In our upcoming blogs we will see more about Java Programming and other opensource technologies.








Thanks for reading !
Being Java Guys Team


In today's discussion we will came across 'How to upload files to FTP server in Java'. We are using 'apache commons-net' API that holds all necessary classes to deal with FTP operations like, create connection , get list of all files on ftp , upload file to ftp , download files from ftp , create and delete a directory on ftp and delete a file on ftp.

In this particular blog we will see an example of How to upload files to FTP server in Java, all steps included in the process are:

1)  Get a 'FtpClient' object from 'org.apache.commons.net.ftp.FTPClient' Class.
2)  Use 'connect()'  method of API to open a connection to the FTP Server, pass ftp path or url as           parameter to connect() method.
3)  Call login() method of API on ftpClient, and pass server credentials as parameter. It returns 'true' if login is successful and false otherwise.
4)  Get FileInputStream object by reading file that needs to be uploaded.
5)  Call storeFile(String remote, InputStream local) method of API on ftpClient, and pass desired file name(name of uploaded file on server) as first argument and pass input stream of uploading file as second argument.
6)  Call logout() method of API on ftpClient to logout from connected ftp server. It returns 'true' if logout is successful and false otherwise.
7)  Call disconnect() method of API on ftpClient to end connection from connected ftp server. It returns 'true' if disconnect is successful and false otherwise.


Required Libraries to add


To use implementation of 'Commons Net' we need to add following dependency to our pom.xml. Here 'commons-net' is required dependency but 'commons-io' is optional. 'commons-io' provides a number of general purpose implementation to deal with IO.
 <dependencies>
  <dependency>
   <groupId>commons-net</groupId>
   <artifactId>commons-net</artifactId>
   <version>2.0</version>
  </dependency>
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
  </dependency>

 </dependencies>


Upload files to FTP Server in Java - Example Code


package com.beingjavaguys.testftp;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;

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

  // get an ftpClient object
  FTPClient ftpClient = new FTPClient();
  FileInputStream inputStream = null;

  try {
   // pass directory path on server to connect
   ftpClient.connect("nagesh12.5gbfree.com");

   // pass username and password, returned true if authentication is
   // successful
   boolean login = ftpClient.login("username", "password");

   if (login) {
    System.out.println("Connection established...");
    inputStream = new FileInputStream("files/fileToUpload.txt");

    boolean uploaded = ftpClient.storeFile("uploadedFile.txt",
      inputStream);
    if (uploaded) {
     System.out.println("File uploaded successfully !");
    } else {
     System.out.println("Error in uploading file !");
    }

    // logout the user, returned true if logout successfully
    boolean logout = ftpClient.logout();
    if (logout) {
     System.out.println("Connection close...");
    }
   } else {
    System.out.println("Connection fail...");
   }

  } catch (SocketException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    ftpClient.disconnect();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}



Output : Here is expected output, connection started, file uploaded to server and connection ends.



Here we are done with 'Upload files to FTP Server in Java - Using Commons Net API'. In our upcoming blogs we will see more about Java Programming and other opensource technologies.








Thanks for reading !
Being Java Guys Team


In today's discussion we will came across 'How to get list of files from FTP server in Java'. We are using 'apache commons-net' API that holds all necessary classes to deal with FTP operations like, create connection , get list of all files on ftp , upload file to ftp , download files from ftp , create and delete a directory on ftp and delete a file on ftp.

In this particular blog we will see an example of how to get list of files from FTP server in Java, all steps included in the process are:

1)  Get a 'FtpClient' object from 'org.apache.commons.net.ftp.FTPClient' Class.
2)  Use 'connect()'  method of API to open a connection to the FTP Server, pass ftp path or url as           parameter to connect() method.
3)  Call login() method of API on ftpClient, and pass server credentials as parameter. It returns 'true' if login is successful and false otherwise.
4)  Use listFiles() to get an array of file information from the currently working directory.
5)  Call logout() method of API on ftpClient to logout from connected ftp server. It returns 'true' if logout is successful and false otherwise.
6)  Call disconnect() method of API on ftpClient to end connection from connected ftp server. It returns 'true' if disconnect is successful and false otherwise.


Required Libraries to add


To use implementation of 'Commons Net' we need to add following dependency to our pom.xml. Here 'commons-net' is required dependency but 'commons-io' is optional. 'commons-io' provides a number of general purpose implementation to deal with IO.
 <dependencies>
  <dependency>
   <groupId>commons-net</groupId>
   <artifactId>commons-net</artifactId>
   <version>2.0</version>
  </dependency>
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
  </dependency>

 </dependencies>


Get list of files from FTP Server in Java - Example Code


package com.beingjavaguys.testftp;

import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

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

  // get an ftpClient object
  FTPClient ftpClient = new FTPClient();

  try {
   // pass directory path on server to connect
   ftpClient.connect("nagesh12.5gbfree.com");

   // pass username and password, returned true if authentication is
   // successful
   boolean login = ftpClient.login("username", "password");

   if (login) {
    System.out.println("Connection established...");

    // get all files from server and store them in an array of
    // FTPFiles
    FTPFile[] files = ftpClient.listFiles();

    for (FTPFile file : files) {
     if (file.getType() == FTPFile.FILE_TYPE) {
      System.out.println("File Name: "
        + file.getName()
        + " File Size: "
        + FileUtils.byteCountToDisplaySize(file
          .getSize()));
     }
    }

    // logout the user, returned true if logout successfully
    boolean logout = ftpClient.logout();
    if (logout) {
     System.out.println("Connection close...");
    }
   } else {
    System.out.println("Connection fail...");
   }

  } catch (SocketException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    ftpClient.disconnect();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}


Output : Here is expected output, connection started, files name and size printed and connection ends.



Here we are done with 'Get list of files from FTP Server in Java - Using Commons Net API'. In our upcoming blogs we will see more about Java Programming and other opensource technologies.








Thanks for reading !
Being Java Guys Team


In today's discussion we will came across 'How to establish connection with FTP server in Java'. We are using 'apache commons-net' API that holds all necessary classes to deal with FTP operations like, create connection , get list of all files on ftp , upload file to ftp , download files from ftp , create and delete a directory on ftp and delete a file on ftp.

In this particular blog we will see an example of how to connect to ftp server in java, all steps included in the process are:

1)  Get a 'FtpClient' object from 'org.apache.commons.net.ftp.FTPClient' Class.
2)  Use 'connect()'  method of API to open a connection to the FTP Server, pass ftp path or url as           parameter to connect() method.
3)  Call login() method of API on ftpClient, and pass server credentials as parameter. It returns 'true' if login is successful and false otherwise.
4)  Call logout() method of API on ftpClient to logout from connected ftp server. It returns 'true' if logout is successful and false otherwise.
5)  Call disconnect() method of API on ftpClient to end connection from connected ftp server. It returns 'true' if disconnect is successful and false otherwise.


Required Libraries to add


To use implementation of 'Commons Net' we need to add following dependency to our pom.xml. Here 'commons-net' is required dependency but 'commons-io' is optional. 'commons-io' provides a number of general purpose implementation to deal with IO.
 <dependencies>
  <dependency>
   <groupId>commons-net</groupId>
   <artifactId>commons-net</artifactId>
   <version>2.0</version>
  </dependency>
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.4</version>
  </dependency>

 </dependencies>


Create connection with FTP server in Java - Example Code


package com.beingjavaguys.testftp;

import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;

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

  // get an ftpClient object
  FTPClient ftpClient = new FTPClient();

  try {
   // pass directory path on server to connect
   ftpClient.connect("nagesh12.5gbfree.com");

   // pass username and password, returned true if authentication is
   // successful
   boolean login = ftpClient.login("nagesh12", "password");

   if (login) {
    System.out.println("Connection established...");
    System.out.println("Status: "+ftpClient.getStatus());
    // logout the user, returned true if logout successfully
    boolean logout = ftpClient.logout();
    if (logout) {
     System.out.println("Connection close...");
    }
   } else {
    System.out.println("Connection fail...");
   }

  } catch (SocketException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    ftpClient.disconnect();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}


Output : Here is expected output, connection started, status string printed and connection ends.



Here we are done with 'Create connection with FTP server in Java - Using Commons Net'. In our upcoming blogs we will see more about Java Programming and other opensource technologies.








Thanks for reading !
Being Java Guys Team


Saturday, 7 December 2013

Java serialization is a mechanism to persist Java objects in a ordered or sequenced form of bytes, it includes objects’s data and object’s type and type of data that is stored in it as well.

Serialization is the mechanism of translating Java object's values and states to bytes to send it over network or to save it on file and disks. On other hand Deserialization is the processs of converting byte code to corresponding java objects.


Serialization and Deserialization in Java


Java serialization API provides mechanism to write an object into streams, disks, db’s or something…. so that the object can be transported over network or can be stored somewhere and can be rebuild again when needed. Getting serialized object again called deserialization.


Need of Serialization


Serialization comes into picture when we need to send an object(not text) over network or store in a file so that the object can be rebuild again when needed. But the network infrastructure and hard disks does not understand java, what they understand are bytes only, and this is what serialization does. It converts java object to bytes and bytes to java object again.


How to Serialize an object in java


All steps are included in the image showing below, lets implement all those steps of serialization one by one to persist a java object to a specified file.



Class to be serialized – Student.java


A class must implement Serializable interface in order to be serialized, this is a marker interface that does not contain any method in it.
package com.beingjavaguys.core;

import java.io.Serializable;

/**
 * @author Nagesh Chauhan
 * 
 */
@SuppressWarnings("serial")
public class Student implements Serializable {

 private static final long serialVersionUID = 1L;

 private int id;
 private String name;

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

}


Serialization Implementation – SimpleSerImpl.java


Here is code for serialization of java objects, we just need to get an FileOutputStream object from the five we want to persist the object and pass this to ObjectOutputStream's object's constructor. Method writeObject() is used to get bytes from java object and pass them to output stream.
package com.beingjavaguys.core;

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

/**
 * @author Nagesh Chauhan
 * 
 */
public class SimpleSerImpl {
 public static void main(String args[]) {

  /*
   * Assigning values to Student classes
   */
  Student student = new Student();
  student.setId(1);
  student.setName("Nagesh Chauhan");

  /*
   * Serializing Student class
   */
  try {
   FileOutputStream fileOutputStream = new FileOutputStream(
     "serialobject.ser");
   ObjectOutputStream objectOutputStream = new ObjectOutputStream(
     fileOutputStream);
   objectOutputStream.writeObject(student);

  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException ioe) {
   // TODO Auto-generated catch block
   ioe.printStackTrace();
  }

 }
}


How to Deserialize an object in java


All steps are included in the image showing below, lets implement all those steps of deserialization one by one to get java object back from the file.



Deserialization Implementation – SimpleSerImpl.java


Here is code for deserialization of java objects, we just need to get an FileInputStream object from the file that contains object's bytes and pass this to ObjectInputStream's object's constructor. Method readObject() returns an object whose bytes are being read from the file.
package com.beingjavaguys.core;

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

/**
 * @author Nagesh Chauhan
 * 
 */
public class SimpleSerImpl {
 public static void main(String args[]) {

  /*
   * Deerializing Student class
   */
  Student studentOut = null;

  try {
   FileInputStream fileInputStream = new FileInputStream(
     "serialobject.ser");
   ObjectInputStream inputStream = new ObjectInputStream(
     fileInputStream);
   studentOut = (Student) inputStream.readObject();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException ioe) {
   // TODO Auto-generated catch block
   ioe.printStackTrace();
  } catch (ClassNotFoundException cnf) {
   // TODO Auto-generated catch block
   cnf.printStackTrace();
  }

  /*
   * Printing values from deserialized object
   */
  System.out.println("Deserailization of Student's object :");
  System.out.println("ID: " + studentOut.getId());
  System.out.println("Name: " + studentOut.getName());

 }
}
Output: Here is expected output, printing values for deserialized object.



Here we are done with Serialization and Deserialization of a simple objcte in java, but in real world applications many other situation may occur. Lets look a little deep in serialization in different scenarios.


What if the serialized object has a reference to another object


In case the object we are going to serialize has some reference to other object, then what would happen ?In this case three possible conditions can arise.


CASE 1: If the referenced class implements Serializable.


In case we have a reference to another object and the referenced class also implements Serializable, that the referenced class will be automatically serialized. In the example below, we have a Employee class that contains EmployeeAddress’s reference in it, in this case the both classes are implementing Serializable interface so both will be serialized.

Class to be serialized - Employee.java


package com.beingjavaguys.core;

import java.io.Serializable;
/**
 * @author Nagesh Chauhan
 * 
 */
public class Employee implements Serializable {
 private int empId;
 private String empName;
 private EmployeeAddress employeeAddress;

 public int getEmpId() {
  return empId;
 }

 public void setEmpId(int empId) {
  this.empId = empId;
 }

 public String getEmpName() {
  return empName;
 }

 public void setEmpName(String empName) {
  this.empName = empName;
 }

 public EmployeeAddress getEmployeeAddress() {
  return employeeAddress;
 }

 public void setEmployeeAddress(EmployeeAddress employeeAddress) {
  this.employeeAddress = employeeAddress;
 }

}


Referenced Class – EmployeeAddress


Here is a simple referenced class 'EmployeeAddress ' this class is being referenced by 'Employee' and implements serializable interface. This class w'll be serialized along with Employee.
package com.beingjavaguys.core;

import java.io.Serializable;
/**
 * @author Nagesh Chauhan
 * 
 */
public class EmployeeAddress implements Serializable {
 
 private String street;
 private String city;
 private String state;
 private String country;
 
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getState() {
  return state;
 }
 public void setState(String state) {
  this.state = state;
 }
 public String getCountry() {
  return country;
 }
 public void setCountry(String country) {
  this.country = country;
 }
 
}


Serialization and De-serialization Implementation



Here is code for serialization and deserialization of java object with a reference to another serializable object. See the implementation below:
package com.beingjavaguys.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
 * @author Nagesh Chauhan
 * 
 */
public class ReferenceSerImpl {
 public static void main(String args[]) {

  /*
   * Assigning values to Employee and EmployeeAdress classes
   */
  Employee emp = new Employee();
  emp.setEmpId(1);
  emp.setEmpName("Nagesh Chauhan");

  EmployeeAddress employeeAddress = new EmployeeAddress();
  employeeAddress.setStreet("Sec-44");
  employeeAddress.setCity("Delhi");
  employeeAddress.setState("Delhi");
  employeeAddress.setCountry("India");

  emp.setEmployeeAddress(employeeAddress);

  /*
   * Serializing Employee class, referenced class EmployeeAdress will be
   * serialized bydefault, unless the referenced class variable is not
   * declared transient
   */
  try {
   FileOutputStream fileOutputStream = new FileOutputStream(
     "serialObject.ser");
   ObjectOutputStream objectOutputStream = new ObjectOutputStream(
     fileOutputStream);
   objectOutputStream.writeObject(emp);

  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException ioe) {
   // TODO Auto-generated catch block
   ioe.printStackTrace();
  }

  /*
   * Deserializing Employee class, referenced class EmployeeAdress will be
   * deserialized bydefault, unless the referenced class variable is not
   * declared transient
   */
  Employee empout = null;

  try {
   FileInputStream fileInputStream = new FileInputStream(
     "serialobject.ser");
   ObjectInputStream inputStream = new ObjectInputStream(
     fileInputStream);
   empout = (Employee) inputStream.readObject();

  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException ioe) {
   // TODO Auto-generated catch block
   ioe.printStackTrace();
  } catch (ClassNotFoundException cnf) {
   // TODO Auto-generated catch block
   cnf.printStackTrace();
  }

  /*
   * Printing values from deserialized object
   */
  System.out.println("Deserailization of Employee and Address :");
  System.out.println("Emp ID: " + empout.getEmpId());
  System.out.println("Emp Name: " + empout.getEmpName());
  System.out.println("Emp Address Street: "
    + empout.getEmployeeAddress().getStreet());
  System.out.println("Emp Address City: "
    + empout.getEmployeeAddress().getCity());
  System.out.println("Emp Address State: "
    + empout.getEmployeeAddress().getState());
  System.out.println("Emp Address Country: "
    + empout.getEmployeeAddress().getCountry());

 }
}
Output: Here is expected output, printing values for deserialized object.


In case the reference class does not implement Serializable it’s variable must be declared transient.


CASE 2: If the referenced class does not implements Serializable but its reference variable is transient.


In case the referenced class EmployeeAddress does not implement Serializable interface, than there will be runtime error in serializing Employee class. To avoid the error just make EmployeeAddress’s reference variable transient.

Transient EmployeeAddress employeeAddress; In this case when we will deserialize Employee class, there will be a null value for EmployeeAddress reference.


CASE 3: If the referenced class can not implement Serializable interface and we still want to persist its states.


In the above two cases we saw, if a reference variable is there either the referenced class must be serializable or the reference variable must be declared transient. Now the question arises, is it possible to persist states of a referenced class even if the class is not serializable and its reference variable is declared transient. Yes, This is possible !

In that case, Java serialization provides a mechnism such that if you have private methods with particular signature then they will get called during serialization and deserialization so we will override writeObject and readObject method of Employee class and they will be called during serialization and deserialization of Employee object.

Object To Serialize – Employee.java


package com.beingjavaguys.com;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
 * @author Nagesh Chauhan
 * 
 */
public class Employee implements Serializable {
 private static final long serialVersionUID = 1L;
 private int empId;
 private String empName;
 transient private EmployeeAddress employeeAddress;

 public int getEmpId() {
  return empId;
 }

 public void setEmpId(int empId) {
  this.empId = empId;
 }

 public String getEmpName() {
  return empName;
 }

 public void setEmpName(String empName) {
  this.empName = empName;
 }

 public EmployeeAddress getEmployeeAddress() {
  return employeeAddress;
 }

 public void setEmployeeAddress(EmployeeAddress employeeAddress) {
  this.employeeAddress = employeeAddress;
 }

 private void writeObject(ObjectOutputStream ous) throws IOException,
   ClassNotFoundException {
  try {
   ous.defaultWriteObject();
   ous.writeObject(employeeAddress.getStreet());
   ous.writeObject(employeeAddress.getCity());
   ous.writeObject(employeeAddress.getState());
   ous.writeObject(employeeAddress.getCountry());

  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 private void readObject(ObjectInputStream ois) throws IOException,
   ClassNotFoundException {
  try {
   ois.defaultReadObject();
   employeeAddress = new EmployeeAddress((String) ois.readObject(),
     (String) ois.readObject(), (String) ois.readObject(),
     (String) ois.readObject());
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}


Reference Object Without Implementing Serializable – EmployeeAddress.java


Here is a simple referenced class 'EmployeeAddress ' this class is being referenced by 'Employee' and does not implements serializable interface.
package com.beingjavaguys.com;

/**
 * @author Nagesh Chauhan
 * 
 */
public class EmployeeAddress{
 
 private String street;
 private String city;
 private String state;
 private String country;
 
 EmployeeAddress(String street, String city, String state, String country){
  super(); 
  this.street = street;
  this.city = city;
  this.state = state;
  this.country = country;
 }
 
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getState() {
  return state;
 }
 public void setState(String state) {
  this.state = state;
 }
 public String getCountry() {
  return country;
 }
 public void setCountry(String country) {
  this.country = country;
 }
 
}


Implementation – Serialization And Deserialization


Here is code for serialization and deserialization of java object with a reference to another non serializable object. See the implementation below:
package com.beingjavaguys.com;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
 * @author Nagesh Chauhan
 * 
 */
public class ReferenceSerImpl {
 public static void main(String args[]) {

  /*
   * Assigning values to Employee and EmployeeAdress classes
   */
  Employee emp = new Employee();
  emp.setEmpId(1);
  emp.setEmpName("Nagesh Chauhan");

  EmployeeAddress employeeAddress = new EmployeeAddress("Sec-44","Delhi","Delhi","India");
//  employeeAddress.setStreet("Sec-44");
//  employeeAddress.setCity("Delhi");
//  employeeAddress.setState("Delhi");
//  employeeAddress.setCountry("India");
//
  emp.setEmployeeAddress(employeeAddress);

  /*
   * Serializing Employee class, referenced class EmployeeAdress will be
   * serialized bydefault, unless the referenced class variable is not
   * declared transient
   */
  try {
   FileOutputStream fileOutputStream = new FileOutputStream(
     "serialObject.ser");
   ObjectOutputStream objectOutputStream = new ObjectOutputStream(
     fileOutputStream);
   objectOutputStream.writeObject(emp);

  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException ioe) {
   // TODO Auto-generated catch block
   ioe.printStackTrace();
  }

  /*
   * Deserializing Employee class, referenced class EmployeeAdress will be
   * deserialized bydefault, unless the referenced class variable is not
   * declared transient
   */
  Employee empout = null;

  try {
   FileInputStream fileInputStream = new FileInputStream(
     "serialobject.ser");
   ObjectInputStream inputStream = new ObjectInputStream(
     fileInputStream);
   empout = (Employee) inputStream.readObject();

  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException ioe) {
   // TODO Auto-generated catch block
   ioe.printStackTrace();
  } catch (ClassNotFoundException cnf) {
   // TODO Auto-generated catch block
   cnf.printStackTrace();
  }

  /*
   * Printing values from deserialized object
   */
  System.out.println("Deserailization of Employee and Address :");
  System.out.println("Emp ID: " + empout.getEmpId());
  System.out.println("Emp Name: " + empout.getEmpName());
  System.out.println("Emp Address Street: "
    + empout.getEmployeeAddress().getStreet());
  System.out.println("Emp Address City: "
    + empout.getEmployeeAddress().getCity());
  System.out.println("Emp Address State: "
    + empout.getEmployeeAddress().getState());
  System.out.println("Emp Address Country: "
    + empout.getEmployeeAddress().getCountry());

 }
}
Output: Here is expected output, printing values for deserialized object.




Here we are done with 'Serialization and Deserialization in Java'. In our upcoming blogs we will see more about Java Programming and other opensource technologies.








Thanks for reading !
Being Java Guys Team


Saturday, 30 November 2013

In our previous discussions we came across, Serialization, serialVersionUID and transient variable. In this particular blog we will see ‘Inheritance in Serialization’.


In case of inheritance, when we want to serialize an object there may be three possible scenarios.

(1) If Super class is Serializable


In case super class is Serializable than all its subclasses will be serializable by default. No need to implement serializable interface in subclass explicitly. See the implementation below.

\src\com\beingjavaguys\core\Human.java

package com.beingjavaguys.core;

import java.io.Serializable;

/**
 * @author Nagesh Chauhan
 */
public class Human implements Serializable {

 private static final long serialVersionUID = 1L;

 String gender;
 String color;

 Human(String gender, String color) {
  this.gender = gender;
  this.color = color;
 }

 public String getGender() {
  return gender;
 }

 public void setGender(String gender) {
  this.gender = gender;
 }

 public String getColor() {
  return color;
 }

 public void setColor(String color) {
  this.color = color;
 }

}


\src\com\beingjavaguys\core\Man.java

package com.beingjavaguys.core;

/**
 * @author Nagesh Chauhan
 */
public class Man extends Human {

 private String name;
 private String address;

 Man(String gender, String color, String name, String address) {
  super(gender, color);
  this.name = name;
  this.address = address;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

}


\src\com\beingjavaguys\core\Implementation.java

package com.beingjavaguys.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author Nagesh Chauhan
 */
public class Implementation {
 public static void main(String args[]) {

  /*
   * Assigning values to Man class's instance
   */
  Man man = new Man("Male", "Black", "Anderw", "Delhi");

  /*
   * Serializing Man's instance
   */
  try {
   FileOutputStream fileOutputStream = new FileOutputStream(
     "serialObject.ser");
   ObjectOutputStream objectOutputStream = new ObjectOutputStream(
     fileOutputStream);
   objectOutputStream.writeObject(man);

  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException ioe) {
   // TODO Auto-generated catch block
   ioe.printStackTrace();
  }

  /*
   * Deserializing Man's instance
   */
  Man manout = null;

  try {
   FileInputStream fileInputStream = new FileInputStream(
     "serialobject.ser");
   ObjectInputStream inputStream = new ObjectInputStream(
     fileInputStream);
   manout = (Man) inputStream.readObject();

  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException ioe) {
   // TODO Auto-generated catch block
   ioe.printStackTrace();
  } catch (ClassNotFoundException cnf) {
   // TODO Auto-generated catch block
   cnf.printStackTrace();
  }

  /*
   * Printing values from deserialized Man's object
   */
  System.out.println("Printing value of Deserailized Man's instance :");
  System.out.println("Gender: " + manout.getGender());
  System.out.println("Color: " + manout.getColor());
  System.out.println("Name: " + manout.getName());
  System.out.println("Address: " + manout.getAddress());

 }

}

Output: Here is expected output, printing values for deserialized object.



(2) If Super class is not Serializable but subclass is


In case super class is not Serializable than to serialize the subclass’s object we must implement serializable interface in subclass explicitly. In this case the superclass must have a no-argument constructor in it. See the implementation below.

\src\com\beingjavaguys\core\Human.java

package com.beingjavaguys.core;

/**
 * @author Nagesh Chauhan
 */
public class Human {
 String gender;
 String color;

 Human() {
 }

 Human(String gender, String color) {
  this.gender = gender;
  this.color = color;
 }

 public String getGender() {
  return gender;
 }

 public void setGender(String gender) {
  this.gender = gender;
 }

 public String getColor() {
  return color;
 }

 public void setColor(String color) {
  this.color = color;
 }

}


\src\com\beingjavaguys\core\Man.java

package com.beingjavaguys.core;

import java.io.Serializable;

/**
 * @author Nagesh Chauhan
 */
public class Man extends Human implements Serializable {

 private static final long serialVersionUID = 1L;
 private String name;
 private String address;

 Man(String gender, String color, String name, String address) {
  super(gender, color);
  this.name = name;
  this.address = address;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

}


\src\com\beingjavaguys\core\Implementation.java

package com.beingjavaguys.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author Nagesh Chauhan
 */
public class Implementation {
 public static void main(String args[]) {

  /*
   * Assigning values to Man class's instance
   */
  Man man = new Man("Male", "Black", "Anderw", "Delhi");

  /*
   * Serializing Man's instance
   */
  try {
   FileOutputStream fileOutputStream = new FileOutputStream(
     "serialObject.ser");
   ObjectOutputStream objectOutputStream = new ObjectOutputStream(
     fileOutputStream);
   objectOutputStream.writeObject(man);

  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException ioe) {
   // TODO Auto-generated catch block
   ioe.printStackTrace();
  }

  /*
   * Deserializing Man's instance
   */
  Man manout = null;

  try {
   FileInputStream fileInputStream = new FileInputStream(
     "serialobject.ser");
   ObjectInputStream inputStream = new ObjectInputStream(
     fileInputStream);
   manout = (Man) inputStream.readObject();

  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException ioe) {
   // TODO Auto-generated catch block
   ioe.printStackTrace();
  } catch (ClassNotFoundException cnf) {
   // TODO Auto-generated catch block
   cnf.printStackTrace();
  }

  /*
   * Printing values from deserialized Man's object
   */
  System.out.println("Printing value of Deserailized Man's instance :");
  System.out.println("Gender: " + manout.getGender());
  System.out.println("Color: " + manout.getColor());
  System.out.println("Name: " + manout.getName());
  System.out.println("Address: " + manout.getAddress());

 }

}


Output: Here is expected output, printing values for deserialized object.



If superclass is not Serializable then all values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. As we can see in the output figure above ‘Gender’ gets a default value and ‘Color’ is getting null because of no default value set.


(3) If the superclass is serializable but we don’t want the subclass to be serialized.


To prevent subclass from being serialized we must implement writeObject() and readObject() method and need to throw NotSerializableException from these methods.

Here we are done with 'Inheritance in Java Serialization'. In our upcoming blogs we will see more about Java Programming and other opensource technologies.








Thanks for reading !
Being Java Guys Team


Sunday, 24 November 2013

In our previous discussions we came across ‘Byte Streams’ and ‘Character Streams’ in Java. In this particular blog we will dive into ‘Buffered Streams’. We will come to know how to read from and write to a file in java using ‘Bufferd Streams’ and why this is a good practice to use buffered streams over byte and character streams.


In case of ‘byte’ and ‘character’ streams every byte or piece of data that s being read or write requires an direct support from underlying OS because of not having an intermediate buffer included. This makes a extensive use of memory and resources. On the other hand Buffered streams works as a wrapper to hold unbuffered streams and make it possible to store bunch of data or bytes in buffers (memory). The underlying OS resource are needed only when the buffer is full or empty and not on every instance of read or write.

The native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full. Unbuffered streams can be converted to buffered streams by wrapping them in a constructor of Bufferd Stream class as shown below.


Convert ‘byte Stream’ to ‘Buffered byte Stream’

Read and Write file using ‘BufferedInputStream’ and


‘BufferedOutputStream’ classes. ‘BufferedInputStream’ and BufferedOutputStream’ clases are used to make buffered byte streams by wrapping InputStreamReader and OutputStreamWriter classes.
package com.beingjavaguys.core;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * @author Nagesh Chauhan
 * 
 */
public class BufferedIOStream {
 public static void main(String args[]) throws IOException {
  BufferedInputStream bis = null;
  BufferedOutputStream bos = null;

  try {
   bis = new BufferedInputStream(new FileInputStream(
     "files/source.txt"));
   bos = new BufferedOutputStream(new FileOutputStream(
     "files/destination.txt"));
   int data;
   while ((data = bis.read()) != -1) {
    System.out.println(data);
    bos.write(data);
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } finally {
   if (bis != null)
    bis.close();
   if (bos != null)
    bos.close();
  }
 }
}




Convert ‘character Stream’ to ‘Buffered character Stream’

Read and Write file using ‘BufferedReader’ and ‘BufferedWriter’ classes.


‘BufferedReader’ and BufferedWriter’ clases are used to make buffered character streams by wrapping ‘FileReader’ and ‘FileWriter’ classes.
package com.beingjavaguys.core;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
 * @author Nagesh Chauhan
 * 
 */
public class BufferedReadWriteStream {
 public static void main(String srgs[]) throws IOException {
  BufferedReader bufReader = null;
  BufferedWriter bufWriter = null;

  try {
   bufReader = new BufferedReader(new FileReader("files/source.txt"));
   bufWriter = new BufferedWriter(new FileWriter(
     "files/destination.txt"));
   String data;
   while ((data = bufReader.readLine()) != null) {
    System.out.println(data);
    bufWriter.write(data);
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } finally {
   if (bufReader != null)
    bufReader.close();
   if (bufWriter != null)
    bufWriter.close();
  }
 }
}



Here we are done with 'Read and Write a file in Java using 'Byte Buffered Streams' and 'Character Buffered Streams'. In our upcoming blogs we will see more about Java Programming and other opensource technologies.








Thanks for reading !
Being Java Guys Team