wellnwill Marathahalli Bangalore

JAVA Input/Output


Input/Output is the medium to dynamically interact with user. In java, there is no direct interaction with i/o devices. Java uses the concept of stream to work with i/o devices. All the stream classes are available in java.io package.


A stream represents flow of data from one place to other place in the form of sequence of bits. Programmatically the functionality of stream is represented by object.

Advantage of Stream

  • Stream provides abstraction by hiding the internal details of I/O operations.
  • Stream improves the efficiency of I/O operation by using Buffering concept.

Types of file

There are two types of file. 1. Text file/character file – Use character oriented classes. To read data – Reader classes. To write data – Writer classes . 2. Binary file – Byte oriented classes. To read data – InputStream classes. To write data – OutputStream classes .

File class

We can create any type of file using File class in java. Ex-txt file, doc file, html file etc.


import java.io.File;
public class LearnFile 
{
  static String pathname = null;
  static File f = null;
  public static void main(String[] args)
  {
   pathname = "D:/program/io";
   f = new File(pathname);
   if(f.exists())
   {
   System.out.println("File or Directory exists.");
    if(f.isFile())
     {
      System.out.println("This is file.");
      if(f.canRead())
       {
       System.out.println("File is readable.");
       }
	if(f.canWrite())
	{
	System.out.println("File is writable.");
        }
     }
			
    else if(f.isDirectory())
    {
     System.out.println("This is directory.");
	if(f.canRead())
	 {
	  System.out.println("Directory is readable.");
	 }
	if(f.canWrite())
	{
	System.out.println("Directory is writable.");
	}
    }
   }
   else
   {
   System.out.println("No such File or Directory exists.");
   }
  }
}
import java.io.*;
public class LearnFile1 
{
      static String pathname = null;
      static File f = null;
      
  public static void main(String[] args) throws IOException
  {
	pathname = "D:/program/io/first.txt";
	f = new File(pathname);
	
	if(f.exists())
	{
		System.out.println("File or Directory exists.");

	}
	else 
	{
	f.createNewFile();   // this method throws IOException
	System.out.println(f.exists());
	}
	}
}






















import java.io.*;
public class LearnFile2 
{
     static String pathname = null;
     static File f = null;
     
	public static void main(String[] args)
	{
	pathname = "D:/program/io/io1";
	f = new File(pathname);
	if(f.exists())
	{
		System.out.println("File or Directory exists.");

	}
	else 
	{
	f.mkdir();   // this method does not throws Exception
	System.out.println(f.exists());
	}
	}
}
import java.io.*;
class Test3
{
 static File f1=null;
 public static void main(String args[]) throws IOException
 {
  f1=new File("writeTofile.txt");
  FileWriter fout=new FileWriter(f1);
  fout.write("There is problem with filewriter that \n");
  fout.write("\n");
  fout.write("we have to insert line separater manually \n");
  fout.write("so sad");
  fout.flush(); // this method throws Exception
  fout.close(); // this method throws Exception
  System.out.println("done");
 }
}






There is problem with filewriter that we have to insert line separater(\n) manually which is varied from system to system. To overcome this problem, We use BufferedWriter and PrintWriter classes.


Writing data into text file:BufferedWriter

We use BufferedWriter to write character data into the file. BufferedWriter cannot communicate directly with the file. It communicate via some writer class object. By using BufferedWriter and BuffedReader class, we can improve the performance of i/o processing. We can use BufferedWriter to write data in the form of text to the file by using some writer object The FileWriter object will be closed automatically when we close BufferedWriter object.

import java.io.*;
public class WriteToTextFile1 
{
             static FileWriter fw = null;
	static BufferedWriter bw = null;
	
	public static void main(String[] args) 
	{
		try 
		{
			 fw=new FileWriter("MyTextFile.txt",false);
			 bw =new BufferedWriter(fw);
			 bw.write("maths score");
			 bw.newLine();
			 bw.write(97);
			 char c[]={'x','y','z'};
			 bw.write(c);
			 System.out.println("great");
		} 
		catch (IOException e) {
			
			e.printStackTrace();
		}
		finally
		{
			if(bw != null)
			{
				try 
				{ 
				    bw.flush();
					bw.close();
				} 
				catch (IOException e)
				{
				
					e.printStackTrace();
				}
			}
	
		}
		
		

	}

}


Reading data from text file:FileReader

import java.io.*;
public class ReadFromTextFile 
{
    static File f = null;
	static FileReader fr=null;
	
	public static void main(String[] args) 
	{
		f=new File("MyTextFile.txt");
		try
		{
			 fr=new FileReader(f);
		     char c[]=new char[(int)f.length()];
             fr.read(c);
             String data=new String(c);
             System.out.println(data);
		} 
		catch(IOException e) 
		{
         e.printStackTrace();
        }
		finally
		{
			if(fr != null){
				try 
				{
					fr.close();//connection will be closed but object is available.
					fr=null;// object will be garbage collected.
				} 
				catch (IOException e) 
				{
					
					e.printStackTrace();
				}
			}
			
		}
		
		

	}

}


Reading data from text file:BufferedReader

We can read data character by character by using FileReader. It is always better to use BufferedReader to read character data from the file by line by line.

import java.io.*;
public class ReadFromTextFile1
{
    static FileReader  f = null;
    static BufferedReader br=null;
	
	public static void main(String[] args) 
	{
		try
		{
			 f=new FileReader("MyTextFile.txt");
			 br=new BufferedReader(f);
		             String oneline=br.readLine();
             while(oneline!=null)
             {
              System.out.println(oneline);
              oneline=br.readLine();
             }
		} 
		catch(IOException e) 
		{
         e.printStackTrace();
        }
		finally
		{
			if(br != null){
				try 
				{
					br.close();
				} 
				catch (IOException e) 
				{
					
					e.printStackTrace();
				}
			}
			
		}
		
		

	}

}



BufferedReader cannot communicate directly with the file. It communicate via some Readar class object. The FileReader object will be closed automatically when we close BufferedReader object.

Footer with Map

Top