Q-28: Write a JAVA program to read the contents of a File.
  

Read File Contents


// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science ) import java.io.File; import java.util.Scanner; import java.io.FileNotFoundException; class ReadFileContent { public static void main(String[ ] args) { Scanner input = new Scanner(System.in); System.out.print("Provide Path(C:\\\\..) or Enter File Name with Extension(if present in the same directory): "); String fileName = input.nextLine(); File readMyFile = new File(fileName); try { Scanner s = new Scanner(readMyFile); while(s.hasNextLine()) { String line = s.nextLine(); System.out.println(line); } s.close(); } catch(FileNotFoundException e) { e.printStackTrace(); } } }

OUTPUT

cmd->  javac  ReadFileContent.java
cmd->  java  ReadFileContent


Case-1: (When file present in the same directory)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
Provide Path(C:\\..) or Enter File Name with Extension(if present in the same directory):  SampleToRead.txt
Hello, I'm Anuj
Bachelor of Science (Honours)
Department of Computer Science



Case-2: (When file present in the different directory)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
Provide Path(C:\\..) or Enter File Name with Extension(if present in the same directory):  E:\\Read and Write\\gccxcsd.txt
Welcome to GCC x CSD !!