Skip to content

Instantly share code, notes, and snippets.

@SriramKeerthi
Created January 3, 2016 05:01
Show Gist options
  • Save SriramKeerthi/25b59892eb88b8609970 to your computer and use it in GitHub Desktop.
Save SriramKeerthi/25b59892eb88b8609970 to your computer and use it in GitHub Desktop.
FileLineCount broken up into blocks
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Reads a file from the command line parameter and counts the number of lines in it
* @author Sriram
*/
public class FileLineCount2
{
private static class FileConnector implements Iterator, AutoCloseable
{
private final BufferedReader br;
private String nextLine;
public FileConnector( String fileName ) throws IOException
{
br = new BufferedReader( new FileReader( fileName ) );
nextLine = br.readLine();
}
@Override public boolean hasNext()
{
return nextLine != null;
}
@Override public String next()
{
String lineToReturn = nextLine;
try {
nextLine = br.readLine();
} catch ( IOException e ) {
nextLine = null;
}
return lineToReturn;
}
@Override public void remove()
{
throw new NotImplementedException();
}
@Override public void close() throws IOException
{
br.close();
}
}
private static class Transformers
{
public int transform1( String input )
{
return 1;
}
public int transform2( AtomicInteger count, int increment )
{
return count.addAndGet( increment );
}
}
public static void main( String[] args ) throws Exception
{
AtomicInteger dataSink = new AtomicInteger( 0 );
Transformers tr = new Transformers();
try ( FileConnector fc = new FileConnector( args[0] ) ) {
while ( fc.hasNext() ) {
int resultOfTransform1 = tr.transform1( fc.next() );
tr.transform2( dataSink, resultOfTransform1 );
}
}
System.out.println( "Lines found: " + dataSink.get() );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment