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

4 comments:

Paul Miller said...

It was helpful post to write coding on Java.
Regards,
JAVA Training

Paul Miller said...

Thanks for your informative article. Java is most popular programming language used for creating rich enterprise, desktop and web applications. Keep on updating your blog with such informative post. J2EE Training in Chennai

anitha a said...

I too always learn something new from your post.
Great post….thanks for sharing this profitable data

prasan said...

Thank you Paul and Anitra for giving me such positive energy .