JAVA SP T


Lets dive into snapshot of my programs!💻

10.Get all characters from the file, count number of lines, words, characters and display on the screen

💡Code:

   import java.io.BufferedReader;
              import java.io.FileReader;
              import java.io.IOException;
              import java.util.StringTokenizer;
              
              public class FileStatistics7078 {
                  public static void main(String[] args) {
                      // Replace "your_file_path" with the path to your text file
                      String filePath = "7078.txt";
              
                      try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
                          int lines = 0;
                          int words = 0;
                          int characters = 0;
                          String line;
              
                          while ((line = reader.readLine()) != null) {
                              lines++;
                              characters += line.length();
              
                              // Count words using StringTokenizer
                              StringTokenizer tokenizer = new StringTokenizer(line);
                              words += tokenizer.countTokens();
                          }
              
                          // Display the statistics
                          System.out.println("Number of lines: " + lines);
                          System.out.println("Number of words: " + words);
                          System.out.println("Number of characters: " + characters);
              
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }
              }
              

📸Output :

output