JAVA
with Friends
Monday, November 11, 2013
JAVA CODE TO READ FILE FROM A LAST READ BYTE POSITION OR READ ‘n’ NUMBER OF LINES FROM LAST READ BYTE
public List
retriveMonitorLog(long bytesRead){
String logFileLocation = “D:/MyLogs.log”;
RandomAccessFile randomAccess = null;
try {
File monitorLog = new File(logFileLocation);
randomAccess = new RandomAccessFile( monitorLog, “r” );
long fileSize=randomAccess.length();
if(fileSize>bytesRead){
randomAccess.seek(bytesRead);
}else{
return null;
}
long offSetBytePosition=bytesRead;
if(bytesRead==0){
long startPositionByte = 0L;
//205685 indicates the number of bytes you want to read at the first attempt to read the file
if(fileSize>(205685)){
startPositionByte = fileSize – (205685);
}
randomAccess.seek(startPositionByte);
} else{
randomAccess.seek(offSetBytePosition);
}
StringBuilder builder = new StringBuilder();
String data;
int lineCounter=0;
while((data = randomAccess.readLine())!=null && lineCounter<=1000){
if(data.length()>0){
lineCounter++;
builder.append(data).append(“
”);
}
}
offSetBytePosition = randomAccess.getFilePointer();
ArrayList
logDataList = new ArrayList
(3);
logDataList.add(builder.toString());
logDataList.add(offSetBytePosition);
return logDataList;
}catch(Exception e){
System.out.println();
} finally {
try{
randomAccess.close();
}catch(Exception ex){}
}
return null;
}
}
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment