जावा प्रोग्राम फ़ाइल में मौजूद लाइनों की संख्या की गणना करने के लिए

इस उदाहरण में, हम जावा में किसी फ़ाइल में मौजूद लाइनों की संख्या गिनना सीखेंगे।

इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावा प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:

  • जावा फ़ाइल वर्ग
  • जावा स्कैनर क्लास

उदाहरण 1: स्कैनर प्रोग्राम का उपयोग करके किसी फ़ाइल में लाइनों की संख्या की गणना करने के लिए जावा प्रोग्राम

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

उपरोक्त उदाहरण में, हमने फ़ाइल की प्रत्येक पंक्ति तक पहुंचने nextLine()के लिए Scannerकक्षा की पद्धति का उपयोग किया है। यहाँ, फ़ाइल इनपुट लाइनों की संख्या के आधार पर। फ़ाइल में फ़ाइल होती है, प्रोग्राम आउटपुट दिखाता है।

इस मामले में, हमारे पास निम्न सामग्री के साथ एक फ़ाइल का नाम input.txt है

 First Line Second Line Third Line

इसलिए, हम आउटपुट प्राप्त करेंगे

 कुल पंक्तियों की संख्या: 3

उदाहरण 2: जावा प्रोग्राम 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(); ) ) )

उपरोक्त उदाहरण में,

  • लाइनों () - एक स्ट्रीम के रूप में फ़ाइल की सभी लाइनों को पढ़ें
  • count () - स्ट्रीम में तत्वों की संख्या लौटाता है

यहां, यदि फ़ाइल input.txt में निम्न सामग्री है:

 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.

कार्यक्रम कुल पंक्तियों को मुद्रित करेगा : 3

दिलचस्प लेख...