我需要在給定偏移量所屬的文本中提取整行。例如:由於文本文件中某個單詞的偏移量,java程序應該檢索相應的行號
"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()
}
不過,我需要一個可靠的方式來獲得實際的行不lineNo的.. 。
那是不是可靠? –
從文件中讀取第一個「offset」字節(我假設它是一個字節偏移量?)。然後計算這些字節中的'\ n'字符的數量。 –
要添加到Andy所說的內容中,我會計算字節中System.lineSeperator()字符串的數量,以便更加精確。它不應該引起問題,但使用'System.lineSeperator()'是一個好習慣。 –