Friday 29 June 2012

serialVersionUID in Java Serialization

The serialVersionUID is used for the versioning of serializable objects.The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException.


Explicitly declare a serialVersionUID

A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

 ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification.

Wednesday 27 June 2012

Transient variable in java

Serialization is the process of saving an object state in a storage medium (such as a file, or a memory buffer) or to transmit it over a network connection in binary form.The object can be restored (Deserialization) at a later time, and even a later location. With persistence, we can move an object from one computer to another, and have it maintain its state.

If you mark an instance variable as transient, you're telling the JVM to skip (ignore) this variable when you attempt to serialize the object containing it. If you have variables marked transient, they will not be restored to their original state (unless you implement readObject()), but will instead be given

the default value for that data type.In other words, even if you say

class User implements Serializable {
transient int password = 12345;
}

when the User instance is deserialized, the variable password will be set to a value of 0.Object references marked transient will always be reset to null, regardless of whether they were initialized at the time of declaration in the class.

Tuesday 26 June 2012

Create Directory in Java

We can use java.io.File class for creating directories in Java. A File class object is an abstract representation of file and directory pathnames.

new File("pathname");

Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

The java.io.File class provides many methods for getting information about a file system. Please visit Load a file in Java to learn more about it.

We can use java.io.File class mkdir(), mkdirs() methods for creating directories.

public boolean mkdir()


Creates the directory named by this abstract pathname.

Sunday 24 June 2012

Append data to a text file in Java

One of the common task related to a text file is to append or add some contents to the file.We can do this in Java using a FileWriter class. This class has a constructor that accept a boolean parameter called append. By setting this value to true, it will keep the existing content and append the new content in the end of the file. I.e

new FileWriter(file)

  • Creates a new file if the specified file not exist.
  • If file already exist, erase the content and open it.

new FileWriter(file, true)

  • Creates a new file if the specified file not exist.
  • If file already exist, open it by keeping the existing content and                                               append the content at the end of the file.

Using DataInputStream and DataOutputStream in Java

A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.

The data input stream is implemented using the class java.io.DataInputStream and data output stream is implemented using the class java.lang.DataOutputStream. Both of this class have the corresponding method to write primitive data and read it back.Using this class make it easier to read integer, float, double data and others without needing to interpret if the read data should be an integer or a float data. Let us discuss about these two classes



Class: public class DataInputStream extends FilterInputStreamimplements DataInput

Constructor: public DataInputStream(InputStream in)

Creates a DataInputStream that uses the specified underlying InputStream.


DataInputStream provided methods for reading primitive data types.

Saturday 23 June 2012

Reading and writing binary files in Java

Byte streams are generally designed to deal with "raw" data (like image file,mp3 etc.) from a file or stream.A byte stream access the file byte by byte. A byte stream is suitable for any kind of file, however not quite appropriate for text files. For example, if the file is using a Unicode encoding and a character is represented with two bytes, the byte stream will treat these separately and you will need to do the conversion yourself.


Byte streams are implemented by the java.io.InputStream and java.io.OutputStream classes and their subclasses.We can use java.io.FileInputStream and java.io.FileOutputStream classes for reading and writing binary file.


Example

 1) Copy an Image file using FileInputStream and FileOutputStream

The following code reads an image file mca1.png using FileInputStream and copies it using FileOutputStream.


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyImage {

    /**
     * @param args
     * @throws IOException
     **/
    public static void main(String[] args) {
        FileInputStream fin = null;
        FileOutputStream fout = null;

        try {
            fin = new FileInputStream("/home/radhakrishnan/Desktop/img.png");
            fout = new FileOutputStream("/home/radhakrishnan/Desktop/img_copy.png");
            int ch;
            while ((ch = fin.read()) != -1) {
                fout.write(ch);
            }
            System.out.println("Image copy completed");
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            try {
                fin.close();
                fout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}


The output is

Image copy completed


Buffered Byte Streams


The above example uses unbuffered I/O. This means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive.

To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as abuffer; 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.

A program can convert an unbuffered stream into a buffered stream, where the unbuffered stream object is passed to the constructor for a buffered stream class. There are two buffered stream classes used to wrap unbuffered byte streams: BufferedInputStream and BufferedOutputStream create buffered byte streams.

Example

 2) Copy an Image file using BufferedInputStream and BufferedOutputStream


The following code reads an image file img.png using BufferedInputStream and copies it using
BufferedOutputStream.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyImageUsingBuffer {

 /**
  * @param Pass
  * @throws IOException
  **/
 public static void main(String[] args) {
  BufferedInputStream in = null;
  BufferedOutputStream out = null;
  int b;
  try {
   in = new BufferedInputStream(new FileInputStream(
     "/home/radhakrishnan/Desktop/img.png"));
   out = new BufferedOutputStream(new FileOutputStream(
     "/home/radhakrishnan/Desktop/img1.png"));

   while ((b = in.read()) != -1) {
    out.write(b);
   }

  } catch (IOException e) {
   System.out.println(e);
  } finally {
   try {
    in.close();
    out.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }

}

Read and Write to file line by line in Java

We can use java.io.BufferedReader and java.io.BufferedWriter classes for efficiently reading and writing text file line by line.The java.io.BufferedReader and java.io.BufferedWriter classes provide internal character buffers. Text that's written to a buffered writer is stored in the internal buffer and only written to the underlying writer when the buffer fills up or is flushed.Likewise, reading text from a buffered reader may cause more characters to be read than were requested; the extra characters are stored in an internal buffer. Future reads first access characters from the internal buffer and only access the underlying reader when the buffer is emptied.

public class BufferedReader extends Reader

The java.io.BufferedReader class is a subclass of java.io.Reader that is chained to another Reader class to buffer input.This allows more efficient reading of characters and lines.The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

There are two constructors. One has a default buffer size (8192 characters); the other requires the programmer to specify the buffer size:

public BufferedReader(Reader in, int buffer_size)
public BufferedReader(Reader in)

Write to file line by line in Java

We can use java.io.BufferedWriter class for efficiently writing text to the file line by line.The java.io.BufferedReader and java.io.BufferedWriter classes
provide internal character buffers. Text that's written to a buffered writer is stored in the internal buffer and only written to the underlying writer when the buffer fills up or is flushed.Likewise, reading text from a buffered reader may cause more characters to be read than were requested; the extra characters are stored in an internal buffer. Future reads first access characters from the internal buffer and only access the underlying reader when the buffer is
emptied.

public class BufferedWriter 
extends Writer
The java.io.BufferedWriter class is a subclass of java.io.Writer that is chained to another Writer class to buffer output.This allows more efficient writing of characters and lines.The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

There are two constructors. One has a default buffer size (8192 characters); the other requires the programmer to specify the buffer size:

public BufferedWriter(Writer in, int buffer_size)
public BufferedWriter(Writer in)

Friday 22 June 2012

Read and Write Unicode File in Java

We can use java.io.InputStreamReader class to read a file in a user-specified decoding and  java.io.OutputStreamWriter class to write a file in a user-specified encoding.

public class InputStreamReader extends Reader


An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.The constructor connects a character reader to an underlying input stream:

public InputStreamReader(InputStream in)
public InputStreamReader(InputStream in, String decoding) throws UnsupportedEncodingException


The first constructor uses the platform's default decoding. The second one uses the specified decoding. For example, to attach an InputStreamReader to System.in with the UTF-8 decoding :

InputStreamReader in = new InputStreamReader(System.in," UTF-8 ");

For top efficiency, consider wrapping an InputStreamReader within a BufferedReader. For example:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in," UTF-8 "));

Read and Write UTF-8 File in Java

We can use java.io.InputStreamReader class to read a file in a user-specified decoding and  java.io.OutputStreamWriter class to write a file in a user-specified encoding.

public class InputStreamReader extends Reader


An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.The constructor connects a character reader to an underlying input stream:

public InputStreamReader(InputStream in)
public InputStreamReader(InputStream in, String decoding) throws UnsupportedEncodingException


The first constructor uses the platform's default decoding. The second one uses the specified decoding. For example, to attach an InputStreamReader to System.in with the UTF-8 decoding :

InputStreamReader in = new InputStreamReader(System.in,"UTF-8");

For top efficiency, consider wrapping an InputStreamReader within a BufferedReader. For example:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in,"UTF-8"));

Thursday 21 June 2012

Read file line by line in Java

We can use java.io.BufferedReader class for efficiently reading a text file line by line.

public class BufferedReader
extends Reader
The java.io.BufferedReader class is a subclass of java.io.Reader that is chained to another Reader class to buffer input.This allows more efficient reading of characters and lines.The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

There are two constructors. One has a default buffer size (8192 characters); the other requires the programmer to specify the buffer size:

public BufferedReader(Reader in, int buffer_size)
public BufferedReader(Reader in)

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

 BufferedReader in = new BufferedReader(new FileReader("t1.txt"));
 
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

BufferedReader is notable for its readLine() method that allows you to read text a line at a time.

Byte streams vs Character streams in Java

Byte streams are generally designed to deal with "raw" data (like image file,mp3 etc.) from a file or stream.A byte stream access the file byte by byte. A byte stream is suitable for any kind of file, however not quite appropriate for text files. For example, if the file is using a Unicode encoding and a character is represented with two bytes, the byte stream will treat these separately and you will need to do the conversion yourself.


A character stream will read a file character by character. The character streams are capable to read 16-bit characters (byte streams read 8-bit characters). Character streams are capable to translate implicitly 8-bit data to 16-bit data or vice versa. Character stream can support all types of character sets ASCII, Unicode, UTF-8, UTF-16 etc.But byte stream is suitable only for ASCII character set.The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set.


Unless you are working with binary data, such as image and sound files, you should use readers and writers (character streams) to read and write information for the following reasons:

Tuesday 19 June 2012

FileInputStream vs FileReader in Java

Java has Two types of streams- Byte & Characters. Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from java.io.InputStream  and java.io.OutputStream.The character streams can be used to perform input and output of text files.Character streams are implemented by the java.io.Reader and java.io.Writer classes and their subclasses.

FileInputStream is meant for reading streams of raw bytes such as image data.

You can use FileReader to read streams of characters like .csv and .txt files as both file types are files that contain characters.

Unless you are working with binary data, such as image and sound files, you should use readers and writers (character streams) to read and write information for the following reasons:

  • They can handle any character in the Unicode character set (while the byte streams are limited to ISO-Latin-1 8-bit bytes).

  • They are easier to internationalize because they are not dependent upon a specific character encoding.

  • They use buffering techniques internally and are therefore potentially much more efficient than byte streams.