我希望程序找到" [DesiredText]"并检查下一行是否为空,如果是,我想采取空行的位置。我看到了一些例子,但我没有正常工作。欢迎提出所有建议和线索。
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
if ((line.contains("[DesiredText]") && br.readLine().isEmpty())) {
RandomAccessFile raf = new RandomAccessFile("D:\\Temp.txt","r");
long position = raf.getFilePointer();
pozycje.add(position);
raf.close();
}
}
答案 0 :(得分:2)
阅读该行,然后检查
if("".equals(line))
或者,如果您不想计算空白区域:
if("".equals(line.trim()))
此外,如果你有while ((line = br.readLine()) != null)
这样的循环由br.readLine()
的值控制,你应该不在循环内再次调用br.readLine()
。这可能会导致您超出循环内部文件的末尾并出现错误。
你应该做的是,当你找到line.contains("[DesiredText]")
时设置一个标志,然后在循环的下一次迭代(下一行)中,如果设置了该标志,你将检查该行是否为空。
答案 1 :(得分:0)
你可以跟踪你到目前为止读过的字符串+换行符的长度,一旦你得到一个空行,长度变量应该给你空行的位置。
答案 2 :(得分:0)
您可以创建两个RandomAccessFiles,其中第二个将比第一个更远一行。类似的东西:
RandomAccessFile first = new RandomAccessFile("D:\\Temp.txt","r");
RandomAccessFile second = new RandomAccessFile("D:\\Temp.txt","r");
String line;
String nextLine = second.readLine();
while (nextLine != null) {
line = first.readLine();
nextLine = second.readLine();
if ((line.contains("[DesiredText]") && nextLine.isEmpty())) {
pozycje.add(first.getFilePointer());
}
}