I dette eksempel lærer vi at tælle antallet af linjer, der findes i en fil i Java.
For at forstå dette eksempel skal du have kendskab til følgende Java-programmeringsemner:
- Java-filklasse
- Java-scannerklasse
Eksempel 1: Java-program til at tælle antallet af linjer i en fil ved hjælp af scannerklassen
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 ovenstående eksempel har vi brugt klassens nextLine()
metode til Scanner
at få adgang til hver linje i filen. Her afhænger af antallet af linjer filen input.txt- filen viser programmet output.
I dette tilfælde har vi et filnavn input.txt med følgende indhold
First Line Second Line Third Line
Så vi får output
Samlet antal linjer: 3
Eksempel 2: Java-program til at tælle antallet af linjer i en fil ved hjælp af 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 ovenstående eksempel
- linjer () - læs alle linjer i filen som en stream
- count () - returnerer antallet af elementer i strømmen
Her, hvis filen input.txt indeholder følgende indhold:
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 udskriver samlede linjer: 3 .