use of com.axway.ats.common.filesystem.FileTailInfo in project ats-framework by Axway.
the class LocalFileSystemOperations method readFile.
/**
* Read file from specific position. Used for file tail.<br/>
*
* <b>NOTE:</b> If the file is replaced with the same byte content, then no change is assumed and 'null' is returned
*
* @param fileName file name
* @param fromBytePosition byte offset. Example: for already read 100 bytes next method call is expected to have 100 as value for this parameter
* return {@link FileTailInfo} object
*/
public FileTailInfo readFile(String fileName, long fromBytePosition) {
RandomAccessFile reader = null;
try {
long position = 0;
boolean isFileRotated = false;
// Open the file for read only
File file = new File(fileName);
try {
reader = new RandomAccessFile(file, "r");
} catch (FileNotFoundException fne) {
throw new FileSystemOperationException("File '" + fileName + "' not found.", fne);
}
long length = file.length();
if (length < fromBytePosition) {
// File was rotated
isFileRotated = true;
position = 0;
} else {
position = fromBytePosition;
}
reader.seek(position);
String line = IoUtils.readLineWithEOL(reader);
if (line != null) {
StringBuilder sb = new StringBuilder(line.length());
while (line != null) {
sb.append(line);
//TODO: consider file encoding
line = IoUtils.readLineWithEOL(reader);
}
position = reader.getFilePointer();
return new FileTailInfo(position, isFileRotated, sb.toString());
}
} catch (Exception e) {
throw new FileSystemOperationException("Could not read file '" + fileName + "' from byte position " + fromBytePosition, e);
} finally {
IoUtils.closeStream(reader);
}
return null;
}
Aggregations