[英]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.