In Java Write a program that reads a file and counts how man

In Java:

Write a program that reads a file and counts how many lines it contains

Solution

sentences.txt (Save the file in the D:Drive.then the path of the file pointing to it is D:\\\\sentences.txt )

sentence 1
sentence 2
sentence 3
sentence 4
sentence 5
sentence 6
sentence 7
sentence 8
sentence 9
sentence 10
sentence 11
sentence 12
sentence 13
sentence 14
sentence 15
sentence 16
sentence 17
sentence 18
sentence 19
sentence 20

______________________________________

CountingNoOfLinesInFile.java

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

public class CountingNoOfLinesInFile {

   public static void main(String args[]) {
      
       //Declaring variables
int count_lines=0;
  
//Assigning the file name to the String variable
       String fname = \"D://lines999.txt\";
      
       //Creating the Scanner class reference
       Scanner sc=null;
      
      
       try{
           //Opening the file
           sc= new Scanner(new File(fname));
          
           //This loops continue to execute until the end of the file
           while (sc.hasNext()){
           sc.nextLine();
          
           //Counting the number of lines
           count_lines++;  
           }

       } catch (IOException e)
       {
           //Displaying the exception
           System.out.println(\"Exception :\"+e);
       }
  
       //Displaying the number of lines in the file
       System.out.println(\"No of Lines in the File :\"+count_lines);
   }

}

______________________________________

Output:

No of Lines in the File :20

________________Thank You

In Java: Write a program that reads a file and counts how many lines it containsSolutionsentences.txt (Save the file in the D:Drive.then the path of the file po
In Java: Write a program that reads a file and counts how many lines it containsSolutionsentences.txt (Save the file in the D:Drive.then the path of the file po

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site