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;

public class JavaProgram
    public static void main(String[] input)
        String fname;
        Scanner scan = new Scanner(;
        /* 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;
            /* 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)
            /* always close the file after use */
        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:

Java Online Test

« Previous Program Next Program »

© Copyright 2021. All Rights Reserved.