Code with Finding: |
class SourceFile {
/**
* Gets the source line for the indicated line number.
*
* @param lineNumber the line number, 1 being the first line of the file.
* @return The line indicated. Does not include the newline at the end
* of the file. Returns {@code null} if it does not exist,
* or if there was an IO exception.
*/
public String getLine(int lineNumber) {
String js = "";
try {
// NOTE(nicksantos): Right now, this is optimized for few warnings.
// This is probably the right trade-off, but will be slow if there
// are lots of warnings in one file.
js = getCode();
} catch (IOException e) {
return null;
}
int pos = 0;
int startLine = 1;
// If we've saved a previous offset and it's for a line less than the
// one we're searching for, then start at that point.
if (lineNumber >= lastLine) {
pos = lastOffset;
startLine = lastLine;
}
for (int n = startLine; n < lineNumber; n++) {
int nextpos = js.indexOf('\n', pos);
if (nextpos == -1) {
return null;
}
pos = nextpos + 1;
}
// Remember this offset for the next search we do.
lastOffset = pos;
lastLine = lineNumber;
return (js.indexOf('\n', pos) == -1) ? null :
js.substring(pos, js.indexOf('\n', pos));
}
}
|