Advertisement
ivana_andreevska

AV5 Word Count (Buffered Reader)

Aug 10th, 2022
891
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. package AV5;
  2.  
  3. import java.io.*;
  4. import java.util.Scanner;
  5.  
  6. public class WordCountTest {
  7.     public static void readDataWithScanner(InputStream inputStream) {
  8.         int lines = 0;
  9.         int words = 0;
  10.         int chars = 0;
  11.         Scanner scanner = new Scanner(inputStream);
  12.  
  13.         while (scanner.hasNextLine()) {
  14.             String line = scanner.nextLine();
  15.             ++lines;
  16.             words += line.split("\\s++").length;
  17.             chars += line.length();
  18.         }
  19.         System.out.printf("Lines : %d , Words: %d , Chars: %d", lines, words, chars);
  20.     }
  21.  
  22.     public static void readDataWithBufferedReader(InputStream inputStream) throws IOException {
  23.         int lines=0;
  24.         int words=0;
  25.         int chars=0;
  26.  
  27.         BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
  28.  
  29.         String line;
  30.  
  31.         while((line=bufferedReader.readLine())!=null)
  32.         {
  33.             ++lines;
  34.             words+=line.split("\\s+").length;
  35.             chars+=line.length();
  36.         }
  37.         System.out.printf("Lines : %d , Words: %d , Chars: %d", lines, words, chars);
  38.     }
  39.  
  40.     public static void main(String[] args) throws IOException {
  41.         File file = new File("C:\\Users\\User\\Desktop\\Napredno Sept\\src\\AV5\\dat");
  42.  
  43.         readDataWithScanner(new FileInputStream(file));
  44.         System.out.println();
  45.         readDataWithBufferedReader(new FileInputStream(file));
  46.     }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement