Table of Contents
Java program to open a file and display the contents
Write a Java program to open a file and display the contents in the console
window.
Program to open a file and display the contents in Java
Text File : itvoyagers.txt
Welcome to ITVoyagers... Do visit itvoyagers.in for practical and notes. Follow us on Instagram and Facebook.
Java File : ReadDemo.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | import java.util.*; import java.io.*; class ReadDemo { String filename, contents; Scanner sc; public ReadDemo() { sc = new Scanner(System.in); } public void getFileName() { System.out.print(" Enter file name with extension (itvoyagers.txt) you want to read : "); filename = sc.nextLine(); } //itvoyagers.in public void displayContent() { try { FileReader fr = new FileReader(filename); BufferedReader br = new BufferedReader(fr); System.out.println(" Content of the file '" + filename + "' n"); while((contents = br.readLine()) != null) { System.out.println(contents); } br.close(); } catch(IOException ex) { System.out.println(" Something went wrong!!! Please check forn 1. If the file name is correctn 2. The file '" + filename + "' does not exist."); } } public static void main(String[] args) { ReadDemo rd = new ReadDemo(); rd.getFileName(); rd.displayContent(); } } |
Output

PRACTICALS/PRACTICE PROGRAM IN Java
CHECKOUT OTHER RELATED TOPICS
We are aiming to explain all concepts of Java in easiest terms as possible.

ITVoyagers
Author