This example will count the number of lines in a text file using java, java 8, guava and apache commons. Each example should take into consideration reading a large file and memory management although I didn't run performance benchmarks. The text was generated using Samuel L. Ipsum .
Setup URI fileLocation ;
@Before
public void setUp () throws URISyntaxException {
fileLocation = this . getClass ()
. getResource ( "/com/levelup/java/io/count-lines-text-file.txt" ). toURI ();
}
File contents Your bones don't break, mine do.
That's clear.
Your cells react to bacteria and viruses differently than mine.
You don't get sick, I do.
That's also clear.
But for some reason, you and I react the exact same way to water.
We swallow it too fast, we choke.
We get some in our lungs, we drown.
However unreal it may seem, we are connected, you and I.
We're on the same curve, just on opposite ends.
Straight up Java @Test
public void count_lines_text_java () throws IOException {
LineNumberReader lineReader = new LineNumberReader ( new FileReader ( Paths
. get ( fileLocation ). toFile ()));
lineReader . skip ( Long . MAX_VALUE );
long totalNumberOfLines = lineReader . getLineNumber () + 1 ;
lineReader . close ();
assertEquals ( 10 , totalNumberOfLines );
}
Java 8 @Test
public void count_lines_text_java8 () throws IOException , URISyntaxException {
long numberOfLines ;
try ( Stream < String > s = Files . lines ( Paths . get ( fileLocation ),
Charset . defaultCharset ())) {
numberOfLines = s . count ();
} catch ( IOException e ) {
throw e ;
}
assertEquals ( 10 , numberOfLines );
}
Google Guava @Test
public void count_lines_text_file_guava () throws IOException {
long linesCounted = com . google . common . io . Files . readLines (
Paths . get ( fileLocation ). toFile (), Charsets . UTF_8 ,
new LineProcessor < Long >() {
long numberOfLinesInTextFile = 0 ;
@Override
public boolean processLine ( String line ) throws IOException {
numberOfLinesInTextFile ++;
return true ;
}
@Override
public Long getResult () {
return numberOfLinesInTextFile ;
}
});
assertEquals ( 10 , linesCounted );
}
Apache Commons @Test
public void count_lines_text_apache () throws IOException {
LineIterator lineIterator = FileUtils . lineIterator (
Paths . get ( fileLocation ). toFile (), Charset . defaultCharset ()
. toString ());
long linesInTextFile = 0 ;
try {
while ( lineIterator . hasNext ()) {
linesInTextFile ++;
lineIterator . nextLine ();
}
} finally {
LineIterator . closeQuietly ( lineIterator );
}
assertEquals ( 10 , linesInTextFile );
}
Count total number of lines in text file posted by Justin Musgrove on 24 February 2015
Tagged: java and java-io
Share on: Facebook Google+
All the code on this page is available on github:
CountLinesTextFile.java