filereader in java

Updated:13/feb/2020 by Computer Hope

The FileReader class of the java.io package can be used to read data from files.

import java.io.*;
class FileExample3
{
	public static void main(String args[]) 
{
    FileReader fr;
    try
    {
    	fr=new FileReader("D:/Assignments/message.txt");
    	int ch;
    	while((ch=fr.read())!=-1)
    	{
    		System.out.print((char)ch);
    	}
    
    }
    catch(FileNotFoundException fnf)
    {
    	System.out.println("Cannot open the file");
    }
catch(IOException ex)
    {
    	System.out.println("Error while reading file");
    }
    finally
    {
    	if(fr!=null)
    	{
    		
    		try
    		{
    			fr.close();
    		}
    		catch(IOException ex)
    		{
    			System.out.println("Error while closing file");
    		}	
    	}
    }
}
}

Second example to print details of Total directory in java

Here we are Showing a detail of directory using java method

That is helpfull to get all info of directory
with this we can doing a looping on this .

import java.io.*;
class FileExample3
{
	public static void main(String args[]) 
{
    FileReader fr=null;
    try
    {
    	fr=new FileReader("D:/Assignments/message.txt");
    	File fobj=new File("D:/Assignments/message.txt");
    	int sz=(int)fobj.length();
    	char []arr=new char[sz];
    	fr.read(arr);
    	String s=new String(arr);
    	System.out.println(s);
    	
    	
    
    }
    catch(FileNotFoundException fnf)
    {
    	System.out.println("Cannot open the file");
    }
catch(IOException ex)
    {
    	System.out.println("Error while reading file");
    }
    finally
    {
    	if(fr!=null)
    	{
    		
    		try
    		{
    			fr.close();
    		}
    		catch(IOException ex)
    		{
    			System.out.println("Error while closing file");
    		}	
    	}
    }
}
}