[英]Given the offset of a word in a text file, the java program should retrieve respective line number
我需要在给定偏移量所属的文本中提取整行。 例如:
"Therapist: Okay. {Pause}
So, how do you feel about -- about this -- about what's going on with your health?
Participant: I don't like it.
There's nothing I can do about it.
{Pause}
Therapist: Yeah.\
15-30-28-0140.raw
Therapist: That doesn't sound so good.
A little bit stressful."
如果我要求offsetNum = 125,则输出将为“参与者:我不喜欢它。”可以看出,应该考虑空行。
我编写了以下代码,该代码可在某些文本文件上使用,但会在其他一些文件上使用(不可靠):
int offset = startingOffset;
try (LineNumberReader r = new LineNumberReader(new FileReader(Input))) {
int count = 0;
while (r.read() != -1 && count < offset)
{
count++;
}
if (count == offset)
{
lineNo = r.getLineNumber()
}
但是,我需要一种可靠的方法来获得实际的线而不是线号...
下面的方法将完成您想要的。
它计算每个字符,包括CR
和LF
字符, line
缓冲区中建立一行文本。 在每一行的末尾,它会检查offsetNum
是否在该行中,包括第一个字符和换行符,如果存在则返回line。 否则,它将清除line
缓冲区并继续下一行。
请注意,如果offsetNum
位于CRLF
对的LF
上,它将返回一个空行,这是不正确的,但我让您找出其中的一个。
private static String readLineAtOffset(String fileName, int offsetNum) throws IOException {
int count = 0;
StringBuilder line = new StringBuilder();
try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName))) {
for (int ch; (ch = reader.read()) != -1; count++) {
if (ch != '\r' && ch != '\n')
line.append((char)ch);
else if (count < offsetNum)
line.setLength(0);
else
break;
}
}
return (count >= offsetNum ? line.toString() : null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.