Tuesday 31 March 2020

Count number of lines in a file

Approach 1: Checking for the character \n.
public static long countLines_1(String filePath) throws IOException {
 if (filePath == null || filePath.isEmpty()) {
  throw new IllegalArgumentException("File name must not null or empty");
 }

 try (InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath))) {

  File file = new File(filePath);

  if (file.length() == 0) {
   return 0;
  }

  byte[] buffer = new byte[1024];
  long count = 0;
  int currentChar = 0;

  while ((currentChar = inputStream.read(buffer)) != -1) {

   for (int i = 0; i < currentChar; ++i) {
    if (buffer[i] == '\n') {
     count++;
    }
   }
  }
  return count;
 }
}

Step 2: Using LineReader.
public long countLines_2(String filePath) throws IOException {
 if (filePath == null || filePath.isEmpty()) {
  throw new IllegalArgumentException("File name must not null or empty");
 }

 try (LineNumberReader reader = new LineNumberReader(new FileReader(filePath))) {
  String lineRead = "";
  while ((lineRead = reader.readLine()) != null) {
  }

  return reader.getLineNumber();
 }

}


App.java

package com.sample.app;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;

public class App {

 public static long countLines_1(String filePath) throws IOException {
  if (filePath == null || filePath.isEmpty()) {
   throw new IllegalArgumentException("File name must not null or empty");
  }

  try (InputStream inputStream = new BufferedInputStream(new FileInputStream(filePath))) {

   File file = new File(filePath);

   if (file.length() == 0) {
    return 0;
   }

   byte[] buffer = new byte[1024];
   long count = 0;
   int currentChar = 0;

   while ((currentChar = inputStream.read(buffer)) != -1) {

    for (int i = 0; i < currentChar; ++i) {
     if (buffer[i] == '\n') {
      count++;
     }
    }
   }
   return count;
  }
 }

 public long countLines_2(String filePath) throws IOException {
  if (filePath == null || filePath.isEmpty()) {
   throw new IllegalArgumentException("File name must not null or empty");
  }

  try (LineNumberReader reader = new LineNumberReader(new FileReader(filePath))) {
   String lineRead = "";
   while ((lineRead = reader.readLine()) != null) {
   }

   return reader.getLineNumber();
  }

 }

 public static void main(String args[]) throws IOException {
  String filePath = "/Users/Shared/data.txt";

  long noOfLines = countLines_1(filePath);

  System.out.println("Number Of Lines : " + noOfLines);
 }

}


You may like

No comments:

Post a Comment