Many time we need to see application log but not for all log but for last line or -n line. As wee know tail in *NIX,solaris,etc have function like tail [-f] filename. And how if we make this future with JAVA code. This time i only give you a simple tail basic function that you have to extend it Here is the code:
public String seek( String fileName , int line) {
try {
java.io.File file = new java.io.File( fileName );
if( !file.exists() ){
System.out.println("File Not Found");
System.exit(0);
}
RandomAccessFile fileHandler = new RandomAccessFile( file, "r" );
long fileLength = file.length() - 1;
int newLineCount = 0;
int carrierLineCount = 0;
StringBuilder sb = new StringBuilder();
for( long filePointer = fileLength; filePointer != -1; filePointer-- ) {
fileHandler.seek( filePointer );
int readByte = fileHandler.readByte();
if( readByte == 0xA ) {
if( filePointer == fileLength ) {
continue;
} else {
newLineCount++;
if( newLineCount == line )
break;
}
} else if( readByte == 0xD ) {
if( filePointer == fileLength - 1 ) {
continue;
} else{
carrierLineCount++;
if( carrierLineCount == line )
break;
}
}
sb.append( ( char ) readByte );
}
String lastLine = sb.reverse().toString();
return lastLine;
} catch( java.io.FileNotFoundException e ) {
e.printStackTrace();
return null;
} catch( java.io.IOException e ) {
e.printStackTrace();
return null;
}
}

0 komentar:
Post a Comment