codescracker


java

Java Program to Read File



« Previous Program Next Program »


Read File

To read the content present inside any file in Java Programming, first you have to ask to the user to enter the file name with extension to open that file to read its content.

Java Programming Code to Read File

Following Java Program ask to the user to enter the file name with extension and then opens that file and read its content to display it on the screen :

/* Java Program Example - Read File */
		
import java.util.Scanner;
import java.io.*;

public class JavaProgram
{
    public static void main(String[] input)
    {
        String fname;
        Scanner scan = new Scanner(System.in);
        
        /* enter the name of the file to read */
        
        System.out.print("Enter File Name to Open (with extension like file.txt) : ");
        fname = scan.nextLine();
        
        /* this will reference only one line at a time */
        
        String line = null;
        try
        {
            /* FileReader reads the text files in the default encoding */
            FileReader fileReader = new FileReader(fname);
            
            /* always wrap the FileReader in BufferedReader */
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            
            while((line = bufferedReader.readLine()) != null)
            {
                System.out.println(line);
            }
            
            /* always close the file after use */
            bufferedReader.close();
        }
        catch(IOException ex)
        {
            System.out.println("Error reading file named '" + fname + "'");
        }
    }
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program to read files

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test