Monday 25 July 2016

Java File IO

In the early 1990s database concept are not very popular, developer mostly use the File IO concept to store data into System Files.

In the 1995s Database concept comes to the picture and large amount of people uses the database concept ,but being a developer we should know the concept of IO & File and why we should go for u Java IO.We can easily access all the  file handling methods in java by using java IO API.In this blog post we will learn about File & IO concept in Java .Before proceeding to File IO we also know about what is File & IO .

"Java I/O (Input/Output) is used to read data from the various sources from(File,Console and Network Streams or Various Servers etc.) and write data to other file or location .Java uses the concept of streams to make I/O operations fast.
"























File:
"
File is an abstract representation of path name.The main component of the File is

1-Prefix according to System OS like Windows prefix should be  "\\\\" and for UNIX  "\" .
2-And group of String to represent File Name or Directory Name.
java.io package contains File and IO classes. "


Application area of Java Input/Output:

If we want to store small amount of data we should always go for Java File IO Concept.

What kind of Data to store File
1-Textual Data
2-Binary Data(Audio files ,Video files,Network Files etc)


Demo Example:

My file existed in Windows locating at C: Drive and file name is Demo.txt so file representation are as follows.

File f=new File("C:\\File Demo.txt");

Note 1:
Many people feel doubt for below statement creates a file to local system but this myth is not true the below code creates instance of File Class not created file in local system.

So i will discuss some most important methods inside File Class:

1-f.exists()
Description:
The above method return type is boolean it checks file existed or not .

2-f.createNewFile()

Description:
 Atomically creates a new, empty file named by this abstract path name if and only if a file with this name does not yet exist.

3-f.isFile()

Description:
This method return type is boolean and Tests whether the file denoted by this abstract path name is a normal file or not.

4-f.isDirectory()

Description:
This method return type is boolean and Tests whether the file denoted by this abstract path name is a directory or not.

5-f.mkdir()

Description:
This method return type is boolean and it creates directory denoted by this abstract path name.

6-f.getName()

Description:
The above method return type is String and return the name of File and Directory defined by abstract path name.

7-f.delete()

Description:
The above method return type is boolean and Deletes the file or directory denoted by this abstract pathname

JDK has two sets of IO packages
1-(java.io package), introduced since JDK 1.0 for stream-based I/O, and
2-The new I/O (java.nio package), introduced in JDK 1.4, for more efficient buffer-based I/O.

There are various readers are available in java.io package.The FileReader is basic reader for reading stream of character data, and the most powerful reader for reading stream of character data is BufferedReader.

Similarly for reading Binary data 

Two most powerful readers to read stream of binary data are 
1-FileInputStream
2-BufferedInputStream


We will discuss the all the above readers one by one with proper example.

Character Data:

1-FileReader:

Class Declaration

public class FileReader extends InputStreamReader

Implemented interfaces
Closeable, AutoCloseable, Readable

FileReader is meant for reading streams of characters.The constructor details of FileReader is given below

1-public FileReader (String fileName) throws FileNotFoundException

Creates FileReader given the name of the file to read from and throws FileNotFoundException if the named file does not exist.

2-public FileReader (File file) throws FileNotFoundException
Creates FileReader ,given the file to read from and throws FileNotFoundException if the named file does not exist.

3-public FileReader (FileDescriptor fd)
Creates a new FileReader, given the FileDescriptor to read from.


Disadvantage

1-The biggest disadvantage of FileReader class is the maximum size of character is taken in int but the length of the file is long so the rest of the content is missing.

2-The second disadvantage is reading the content of the file is char by char not line by line (performance issue)

Demo Example:Reading file using FileReader

package com.navneet.IO;

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

public class FileReaderDemo {

public static void main(String[] args) {
try{
File f=new File("D:\\Navneet Document\\File.txt");

FileReader fr=new FileReader(f);

char [] data1=new char [900];
fr.read(data1);
for(char s:data1){
System.out.println(s);

}


}
catch(IOException ex){

ex.printStackTrace();

}



}

}


BufferedReader:

To overcome the problem encountered in FileReader ,BufferedReader comes to the picture.BufferedReader reads the data line -by- line performance gets increased.Demo Example :If my file contain 1000 mobile phones list so reading mobile phone char by char
is the best practice or read line by line is the best practice.So last method is also good one.
BufferedReader can't communicate with the file it is necessary need any FileReader to communicate with the file.



















Buffering provides most efficient way to read characters,array and lines.The buffer size may be specified if not specified default size may be used.


There are two constructors inside BufferedReader Class:

1-BufferedReader(Reader in)
This constructors creates a buffering character-input stream that uses default buffer sized input buffer.


2-BufferedReader(Reader in, int sz)
This constructor creates the BufferedReader with subordinate streams with specified buffered size.


Important Methods:

1-int read()
This method reads char from inputstream and return int in the range of 0-65535.

2- int read(char[] buf, int offset, int count)
This method reads an array of destination buffer.

Here the above method parameters are

char[] buf=The destination buffer where we store characters
int offset =index of the array to store chars into the destination buffer.
int count =Maximum numbers of characters

3-public String readLine() throws IOException

The method reads a line of text .A line is considered to be terminated any one of the feed line ("\n"),("\r")


4-public long skip(long n) throws IOException
The method used for skips the characters in BufferedReader and returned the number of charcetrs to be skiped.

Demo Example:Reading file using BufferedReader

package BufferedReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class BufferedReaderskipMethodDemo {

public static void main(String[] args) throws IOException {
String data ="ttrewuuwwnnsnsmamauurururururururuhfkkssueieoesoowowgffhhfjfhfjfjfkfkfkfkkfk";
StringReader sr1=null;
BufferedReader br1=null;
     try{
     sr1 = new StringReader(data);
              br1 = new BufferedReader(sr1);

        int i = 0;
        while((i = br1.read()) != -1)
        {
       
           br1.skip(1);    // skips a character
           System.out.print((char)i);
        }
     
     } catch (Exception e) {
     
        // exception occurred.
        e.printStackTrace();
     }finally{
           sr1.close();
     
           br1.close();
     }


}

}


4-public void close() throws IOException

This method closes the stream and releases any System resources associated with it.After invoking(calling) close() method any other methods such as read(),skip(),readLine() not working and invoking on these methods throws IOException.

close() is the method inside Interface Closeable and extends AutoCloseable interface.

Interface Declaration:

public interface Closeable extends AutoCloseable

Method Declaration:
void close() throws IOException



package com.navneet.IO;

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

public class BufferedReaderDemo {

public static void main(String[] args) {

BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("D:\\Navneet Document\\File.txt"));
            String line = reader.readLine();

            while (line!=null) {
                // Print read line
                System.out.println(line);

                // Read next line for while condition
                line = reader.readLine();
            }

        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }





}

}


For Reading Binary Data:

All of the above described Readers for reading text/character data ,and similarly for binary data/raw bytes we will use two most important Readers are
1-FileInputStream
2-BufferedInputStream


1-FileInputStream:
FileInputStream obtains input bytes from a file in a File System.This type of Reader is meant for reading binary data like video files ,audio files and image files not for reading text files.

Various Constructors:
1-FileInputStream (File file)
Creates FileInputStream by opening connection to the File


2-FileInputStream(FileDescriptor fdObj)
Creates FileOInputStream by using the filedescriptor,which representats an existing connection to an actual file system.


3-FileInputStream(String name)
Creates FileInputStream by opening connection to the actual file with filename.


Various Methods of FileInputStream:
1-public int available() throws IOException

This method returns an estimate of the remaining bytes that can be read from inputstream.

 2-public final FileDescriptor getFD() throws IOException
This method returns FileDescriptor object that represents the connection to the actual file in the File System being used by FileInputStream.



3-public FileChannel getChannel()
This method returns FileChannel object associated with the file inputstream.

4-public int read() throws IOException
This method reads byte from this inputstream and returns the next byte of data, or -1 if the end of the file is reached.


5-public int read(byte[] b) throws IOException
 This method reads byte array from this inputstream and returns the next byte of data, or -1 if the end of the file is reached.



Demo Example:
package com.navneet.IO;

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

public class FileInputStreamDemo {

public static void main(String[] args) throws IOException {
FileInputStream fis=null;
int i;
     char ch;
      try{
    fis =new FileInputStream("D:\\Navneet Document\\File.txt");
        byte[] b = new byte[fis.available()];
        i=fis.read(b);
        System.out.println("Number of bytes ="+i);
        for(byte data:b)
        {
           ch=(char)data;
           System.out.print(ch);
        }
   
     }catch(Exception ex){
     
        ex.printStackTrace();
    }
      finally{
    {  
    fis.close();
    }
    }
}
}


2-BufferedInputStream

This is hierarchy of BufferedInputStream and class declaration is

"public class BufferedInputStream extends FilterInputStream "


java.lang.Object
  .java.io.InputStream
    .java.io.FilterInputStream
      .java.io.BufferedInputStream


Just like BufferedReader ,BufferedInputStream provides buffering facility to speed-up the file processing ,and BufferedInputStream can't communicate with the file directly.It also need any Stream Reader


Various Important Constructors

1-BufferedInputStream (InputStream in)
Creates a BufferedInputStream and saves its argument, the input stream in, for later use.

2-BufferedInputStream(InputStream in, int size)
Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in for later use.

Demo Example:

package com.navneet.IO;

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


public class BufferedIOStream {
 public static void main(String args[]) throws IOException {
  BufferedInputStream bis = null;
  BufferedOutputStream bos = null;

  try {
 File f=new File("D:\\Navneet Document\\demofile.txt");
 f.createNewFile();
   bis = new BufferedInputStream(new FileInputStream("D:\\Navneet Document\\File.txt"));
 
   bos = new BufferedOutputStream(new FileOutputStream("D:\\Navneet Document\\demofile.txt"));
   int data;
   while ((data =bis.read())!=-1) {
 char ch=(char)data;
    System.out.println(ch);
   bos.write(ch);
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } finally {
   if (bis != null)
    bis.close();
   if (bos != null)
    bos.close();
  }
 }
}


Writer Class:
The writer class is used for write data to the File.There are various File Writers are available in java.io package here we will discuss most important and most commonly used Writers.In the above described writers the most widely used writers are 

FileWriter,BufferedWriter and PrintWriter for character data ,OutputStreamWriter for byte/binary data.

Before proceeding to discuss various Writers we will discuss Writer Class.

The writer class is the parent class of all the writers like StringWriter, CharArrayWriter ,PipedWriter, FileWriter, OutputStreamWriter.This class implements four interfaces.

1-Closeable
2-Flushable
3-Appendable
4-AutoCloseable

The various important methods supported by Writer class are
1-public void write(int c) throws IOException
 "This method writes single character to the file."

2-public void write(char[] cbuf) throws IOException
"This method writes an array of characters to the file."

3-public abstract void write(char[] cbuf,int off,int len) throws IOException
"This method writes a portion of charactes to the file".
Parameters:
cbuf - Array of characters
off - Offset from which to start writing characters
len - Number of characters to write

4-public void write(String str) throws IOException
"This method write string data to the file."

5-public void write(String str,int off,int len) throws IOException
"This method write a portion of string data to the file."

Parameters:
str - A String
off - Offset from which to start writing characters
len - Number of characters to write
6-public Writer append(CharSequence csq) throws IOException
"This method appends the specified characters to this writer."

7-public Writer append(CharSequence csq,int start,int end) throws IOException
"This method appeneds a subsequent character sequence to this writer."

8-public Writer append(char c) throws IOException
"This method appends the specified character to this writer."

9-public abstract void flush() throws IOException
"This method closes the stream, flushing it first.Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown."

10-public abstract void close() throws IOException
"This method flushes the stream.If the stream has saved or any remaning characters from the various write() methods in a buffer,write them immediately to their destination file."




































1-FileWriter :

"FileWriter is the basic or low level writer to write streams of character/text data to the file.FileWriter class extends OutputStreamWriter class.The  hierarchy of FileWriter class is given below."

java.lang.Object
  java.io.Writer
     java.io.OutputStreamWriter
         java.io.FileWriter

class declaration

public class FileWriter extends OutputStreamWriter

Constructors Details:

There are four constructors for FileWriter Class.

1-FileWriter f=new FileWriter(String filename);
Constructs a FileWriter object with the given a filename.

2-FileWriter f=new FileWriter(File file);
Constructs a FileWriter object with the given a File object.

The above two constructors provide override operation.Execution of above constructor writes fresh content to the file.

For performing append operation other two constructors are added to the FileWriter class are

3-FileWriter f=new FileWriter(String filename,booolean appened);
Constructs a FileWriter object given a file name with a boolean indicating appened operation whether or not to append the data written.

4-FileWriter f=new FileWriter(File file,booolean appened);
Constructs a FileWriter object given a file with a boolean indicating appened operation whether or not to append the data written.

Note:
If the provided filename is not existed this constructor automatically creates the given filename to the physical directory.  

The below hierarchy of FileWriter Class:

Class FileWriter

java.lang.Object
   java.io.Writer
     java.io.OutputStreamWriter
         java.io.FileWriter

Methods of FileWrite Class

1-As we know every class is inherited from object class so Object Class Methods are
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

2-Methods inherited from class java.io.Writer
append, append, append, write, write

3-Methods inherited from class java.io.OutputStreamWriter

close, flush, getEncoding, write, write, write

Disadvantage of FileWriter Class:
1-The biggest disadvantage of FileWriter is to add line separator "\n" manually for writing text data into new line.

2-The other drawback is some system not recognized this ("\n") symbol as a new line.

Demo Example:

package com.navneet.IO;

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterDemo {

public static void main(String[] args){
 
      FileWriter fw=null;;
           try {
fw=new FileWriter("D:\\NavneetDemo.txt",false);
fw.write(100);  // Write char data to the file
fw.write("\n");
char [] ch={'x','y','z'};  // Write an array of char data to the file

fw.write(ch);
fw.write("\n");
String str="This is demo sample";
fw.write(str);  // Write string data to the file
fw.write("\n");
fw.flush();
       }
    
      catch(IOException io){
 System.out.println(io.getMessage());
       
       }
    finally
         {
    try{
    fw.close();
     }
    catch(IOException ex)
      {
    System.out.println(ex.getMessage());
     }
      }
      
   }


}


2-BufferedWriter:

Class Declaration:
"public class BufferedWriter extends Writer  "

Why we should go for BufferedWriter Class

1-The main disadvantage of FileWriter is adding new line manually which is not good programming practice So BufferedWriter newLine() method solved the problem encountered in FileWriter.

2-Many system does't reconigzed symbol "\n" as a new line.

Note: 
BufferedWriter can't communicate with the File directly it always need any writers like(FileWriter,PrintWriter etc).









Constructors:

There are two constructors are in BufferedWriter class.

1-BufferedWriter bw=new BufferedWriter(Writer w);

2-BufferedWriter bw=new BufferedWriter(Writer w,int buffered size);


Methods:
1-The FileWriter methods available for BufferedWriter class also

FileWriter Methods
------------------------------------
1-write(int ch)
2-write(char[] ch)
3-writer(String str)
4-flush()
5-close()
-----------------------------------
BufferedWriter added method

6-newLine()

"Calling of this method insert line separator to the file"

Note :Many people feel doubt about bw.close() method >Calling of this method automatically closes the any resources associated to the file.There are no need to close 

any other writer object explicitly.




DemoExample:


package com.navneet.IO;

import java.io.*;

public class BufferedWriterDemo {

public static void main(String[] args) {
BufferedWriter bw=null;
FileWriter fw=null;
try{
fw=new FileWriter("D:\\BufferedWriter.txt");
bw=new BufferedWriter (fw);
bw.write(100);
bw.newLine();
char [] ch={'a','b','g','h'};
bw.write(ch);
bw.newLine();
bw.write("BufferedWrite Demo Example By Navneet");
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
finally{
try{
bw.flush();
bw.close();
}
catch(IOException ex){
ex.printStackTrace();
}
}

}

}

3-PrintWriter

PrintWriter is the most powerful and enhanced writer in the java language.PrintWriter gives the facility to write any type of primitive data to the file.The print() 

method is the power of PrintWriter class.

Disadvantage of pervious Writers:
The pervous level of writers faces two biggest problems.
1-The FileWriter uses "\n" symbol for insert line separator manually where as BufferedWriter calls newLine() method for inserting line boths ways are not good 

programming practice.Causes performance and readability.

2-Both writers can't write other primitive data types like (int,double,float,boolean) to the File.If we tried to write this data type to the file program gives error
Demo Example:
if we want to write interger value 100 to the file we write like  this 
write("100");   // Write 100 to the file
write(100);  // Write char 'd' to the file

For writing boolean data to the file we write 

write("true");  //Write true value to the file


Constructor :
According to Java 8 API
1-PrintWriter(File file)
Description:

Creates a new PrintWriter, without automatic line flushing, with the specified file.

2-PrintWriter(File file, String csn)
Description:
Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.

Parameters:
file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output 

will be written to the file and is buffered.

csn - The name of a supported charset

3-PrintWriter(OutputStream out)
Description:
Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.

4-PrintWriter(OutputStream out, boolean autoFlush)
Description:
Creates a new PrintWriter from an existing OutputStream.

5-PrintWriter(String fileName)
Description:
Creates a new PrintWriter, without automatic line flushing, with the specified file name.

6-PrintWriter(String fileName, String csn)
Description:
Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset.

csn - The name of a supported charset

7-PrintWriter(Writer out)
Description:
Creates a new PrintWriter, without automatic line flushing.

8-PrintWriter(Writer out, boolean autoFlush)
Description:
Creates a new PrintWriter.

PrintWriter Methods:

The PrintWriter's print method solves the biggest problem encounterd in both the writers.Here we will describe all methods of PrintWriter Class.

FileWriter Class Methods:
---------------------------
1-writer(int ch);
2-writer(char [] ch);
3-writer(String str);
4-flush()
5-close()
----------------------------

----------------------------
Print Methods of PrintWriter:
---------------------------

1-pw.print(100);                                 // Write 100 to the file without line separation  
2-pw.print('c');                                // Write char data to the file without line separation 
3-pw.print("Print method of PrintWriter");      // Write string data to the file without line separation 
4-pw.print(34.6);                               // Write double data to the file without line separation 
5-pw.print(true);                               // Write boolean data to the file without line separation 
6-pw.print(ch);                                 // Write char array to the file without line separation 
==================================
Println Methods of PrintWriter:
==================================

1-pw.println(100);                               // Write 100 to the file with line separation  
2-pw.println('c');                               // Write char data to the file with line separation 
3-pw.println("Print method of PrintWriter");     // Write string data to the file with line separation 
4-pw.println(34.6);                              // Write double data to the file with line separation 
5-pw.println(true);                              // Write boolean data to the file with line separation 
6-pw.println(ch);                                // Write char array to the file with line separation 










package com.navneet.IO;
import java.io.*;

public class PrintWriterDemo {

public static void main(String[] args) {
PrintWriter pw=null;
try{
pw=new PrintWriter("D:\\PrintWriterDemo.txt");
//FileWriter Class methods
pw.write(105);
char [] ch={'a','b','c','r'};
pw.write(ch);
pw.write("PrintWriter Demo Program");

//Various print method of PrintWriter
pw.print(100);
pw.print("c");
pw.print("Print method of PrintWriter");
pw.print(34.6);
pw.print(true);
pw.print(ch);

//Various println method of PrintWriter
pw.println(100);
pw.println("c");
pw.println("Print method of PrintWriter");
pw.println(34.6);
pw.println(true);
pw.println(ch);

}
catch(IOException ex){
System.out.println(ex.getMessage());
}
finally{
pw.flush();
pw.close();

}

}

}


Conclusion :
In the above discussion ,for writing data to the file PrintWriter is the best writer and for reading BufferedReader is the best one.















1 comment:

  1. amazing block sir 'it is very useful to learn java.

    ReplyDelete