English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à calculer le nombre de lignes existantes dans un fichier Java.
import java.io.File; import java.util.Scanner; class Main { public static void main(String[] args) { int count = 0; try { //Créer un nouveau fichier File file = new File("input.txt"); //Créer un objet Scanner //Lié au fichier Scanner sc = new Scanner(file); //Lire chaque ligne, puis //Calculer le nombre de lignes while(sc.hasNextLine()) { sc.nextLine(); count++; } System.out.println("Total number of lines: " + count); // Fermer le scanner sc.close(); } catch (Exception e) { e.getStackTrace(); } } }
Dans l'exemple ci-dessus, nous avons utilisé la méthode nextLine() de la classe Scanner pour accéder à chaque ligne du fichier. Ici, en fonction du nombre de lignes du fichier input.txt, le programme affichera la sortie.
Dans ce cas, le nom de notre fichier est input.txt et il contient le contenu suivant :
Première Ligne Deuxième Ligne Troisième Ligne
Par conséquent, nous obtiendrons la sortie
Nombre total de lignes: 3
import java.nio.file.*; class Main { public static void main(String[] args) { try { //Establish a connection with the file Path file = Paths.get("input.txt"); //Read all lines of the file long count = Files.lines(file).count(); System.out.println("Total number of lines: " + count); } catch (Exception e) { e.getStackTrace(); } } }
In the above example,
lines() - Read all lines of the file in stream form
count() - Return the number of elements in the stream
Here, if the file input.txt contains the following content:
This is an article about Java examples. These examples calculate the number of lines in the file. Here, we use the java.nio.file package.
The program will printTotal number of lines:3.