Java programm failis olevate ridade arvu lugemiseks

Selles näites õpime lugema Java-failis olevate ridade arvu.

Selle näite mõistmiseks peaksid teil olema teadmised järgmistest Java programmeerimise teemadest:

  • Java failiklass
  • Java skanneri klass

Näide 1: Java-programm Scanner-klassi abil faili ridade arvu lugemiseks

 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(); ) ) )

Ülaltoodud näites oleme faili igale reale pääsemiseks kasutanud klassi nextLine()meetodit Scanner. Siin näitab programm väljundit , sõltuvalt faili input.txt ridade arvust .

Sel juhul on meil järgmise sisuga failinimi input.txt

 First Line Second Line Third Line

Niisiis, saame väljundi

 Liinide koguarv: 3

Näide 2: Java-programm failide ridade arvu lugemiseks paketi java.nio.file abil

 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(); ) ) )

Ülaltoodud näites

  • read () - loe faili kõik read voogena
  • count () - tagastab voos olevate elementide arvu

Siin, kui fail input.txt sisaldab järgmist sisu:

 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.

Programm trükib read kokku: 3 .

Huvitavad Artiklid...