Write a JAVA Program which reads a text file from the Command Line and prints it to the console.
SOLUTION:
import java.io.File; import java.io.FileReader; import java.io.BufferedReader; public class FileReadingExample { public static void main(String[] args){ if(args.length!=1){ System.out.println("Please enter file name in proper format."); return; } //File object File file = new File(args[0]); //Checking file if(file.exists()){ System.out.printf("%s exists.",file.getName()); System.out.println(); if(file.isDirectory()){ System.out.println(" But it is not a file."); return; } } else{ System.out.println("File not exists."); return; } //Reading file ... try{ FileReader fileReader = new FileReader(args[0]); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; System.out.println("--------Reading Started-------\n"); while ( (line=bufferedReader.readLine()) != null ) { System.out.println(line); } System.out.println("\n--------Reading Finished-------"); } catch(Exception e) { System.out.println("Invalid file."); } } }
No comments:
Post a Comment