Friday, November 25, 2016

How to write a file reading program in Java.


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileReader{
public static void main(String[]args) throws FileNotFoundException{
//ask user to enter a file name.
Scanner scan = new Scanner(System.in);
System.out.println("Enter a file name.");
//create a file object and pass the file name to it as a parameter
File file = new File(scan.nextLine());
Scanner fileName = new Scanner(file);
while(fileName.hasNextLine()){
String line = fileName.nextLine();
System.out.println(line);
}
fileName.close();
scan.close();
}//end of the main method

}//end of the class TokenReader