Java Program to Read and Display File

« Previous Program Next Program »

Read and Display File

To read and display the contents of a in Java programming, you have to ask to the user to enter the file name with extension to read that file and display its content on the output screen.

Java Programming Code to Read and Display File

In the following Java Program, we have created a file name named file.txt with three line of text. Now let's see the below program to know how to read the file and display its content on the screen.

Java Program to Read and Display File

Following Java Program ask to the user to enter file name with extension (like file.txt) to read and display the content of this file on the screen:

/* Java Program Example - Read and Display File's Contents */
import java.util.Scanner;

public class JavaProgram
    public static void main(String[] input)
        String fname;
        Scanner scan = new Scanner(;
        /* enter filename with extension to open and read its content */
        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 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 read display file content

Here the above Java Program ask to the user to enter file name (like file.txt) to read all the content present in the file and display all its content on the screen

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.