V tem primeru se bomo naučili šteti število vrstic v datoteki v Javi.
Če želite razumeti ta primer, morate poznati naslednje programske teme Java:
- Java File Class
- Razred optičnega bralnika Java
Primer 1: Program Java za štetje števila vrstic v datoteki z uporabo razreda Scanner
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(); ) ) )
V zgornjem primeru smo uporabili nextLine()
metodo Scanner
razreda za dostop do vsake vrstice datoteke. Tu program prikaže izhodne podatke , odvisno od števila vrstic, ki jih vsebuje datoteka input.txt .
V tem primeru imamo ime datoteke input.txt z naslednjo vsebino
First Line Second Line Third Line
Torej, dobili bomo rezultat
Skupno število vrstic: 3
Primer 2: Program Java za štetje števila vrstic v datoteki s pomočjo paketa 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(); ) ) )
V zgornjem primeru je
- lines () - preberite vse vrstice datoteke kot tok
- count () - vrne število elementov v toku
Če datoteka input.txt vsebuje naslednjo vsebino:
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.
Program bo natisnil Total Lines: 3 .