Java-program for å telle antall linjer i filen

I dette eksemplet vil vi lære å telle antall linjer som er tilstede i en fil i Java.

For å forstå dette eksemplet, bør du ha kunnskap om følgende Java-programmeringsemner:

  • Java-filklasse
  • Java skannerklasse

Eksempel 1: Java-program for å telle antall linjer i en fil ved hjelp av skannerklasse

 import java.io.File; import java.util.Scanner; class Main ( public static void main(String() args) ( int count = 0; try ( // create a new file object File file = new File("input.txt"); // create an object of Scanner // associated with the file Scanner sc = new Scanner(file); // read each line and // count number of lines while(sc.hasNextLine()) ( sc.nextLine(); count++; ) System.out.println("Total Number of Lines: " + count); // close scanner sc.close(); ) catch (Exception e) ( e.getStackTrace(); ) ) )

I eksemplet ovenfor har vi brukt nextLine()metoden i Scannerklassen for å få tilgang til hver linje i filen. Her, avhengig av antall linjer filen input.txt- filen inneholder, viser programmet utdataene.

I dette tilfellet har vi et filnavn input.txt med følgende innhold

 First Line Second Line Third Line

Så vi får produksjon

 Totalt antall linjer: 3

Eksempel 2: Java-program for å telle antall linjer i en fil ved hjelp av pakken java.nio.file

 import java.nio.file.*; class Main ( public static void main(String() args) ( try ( // make a connection to the file Path file = Paths.get("input.txt"); // read all lines of the file long count = Files.lines(file).count(); System.out.println("Total Lines: " + count); ) catch (Exception e) ( e.getStackTrace(); ) ) )

I eksemplet ovenfor,

  • linjer () - les alle linjene i filen som en strøm
  • count () - returnerer antall elementer i strømmen

Her, hvis filen input.txt inneholder følgende innhold:

 This is the article on Java Examples. The examples count number of lines in a file. Here, we have used the java.nio.file package.

Programmet vil skrive ut totale linjer: 3 .

Interessante artikler...