Readline Processor
Google Guava is a java library with lot of utilities and reusable components.
This requires the library guava-10.0.jar to be in classpath.
The following example shows using Files.readLines() API.
package com.bethecoder.tutorials.guava.io_tests;
import java.io.File;
import java.io.IOException;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
public class ReadLineProcessorTest {
/**
* @param args
* @throws IOException
*/
public static void main ( String [] args ) throws IOException {
File file = new File ( "C:\\abcd.txt" ) ;
String first4lines = Files.readLines ( file, Charsets.UTF_8, new SimpleLineProcessor ()) ;
System.out.println ( first4lines ) ;
}
}
class SimpleLineProcessor implements LineProcessor<String> {
StringBuilder lineBuf = new StringBuilder () ;
private int lineCount = 0 ;
@Override
public String getResult () {
return lineBuf.toString () ;
}
@Override
public boolean processLine ( String line ) throws IOException {
//read only first 2 lines
//true to continue processing, false to stop
if ( lineCount ++ < 2 ) {
lineBuf.append ( line ) .append ( "\n" ) ;
return true ;
}
return false ;
}
}
It gives the following output,
ABCD
ABCD