Display file contents Learn programming Java

Lesson:

File Management


Exercise:

Display file contents


Objetive:

Create a program to display all the contents of a text file on screen (note: you must use a StreamReader). The name of the file will be entered in the command line or (if there is no command line present) asked to the user by the program.


Code:

package Reader;
import java.util.*;

public class Main
{
	public static void main(String[] args)
	{
		System.out.print("Enter name of file: ");
		String nameFile = new Scanner(System.in).nextLine();

		java.io.FileReader myfile;
	    java.io.BufferedReader myfileBufferedReader = new java.io.BufferedReader(myfile);
		try
		{
			myfile = new java.io.FileReader(nameFile);
			String line = " ";
			do
			{
				line = myfileBufferedReader.readLine();
				if (line != null)
				{
					System.out.println(line);
				}
			} while (line != null);
		}
		catch (RuntimeException e)
		{
			System.out.println("Error al intentar abir el fichero.");
		}
		new Scanner(System.in).nextLine();
	}
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.