public static void main(String[] args) {
File file = new File("D:/123456.txt");
BufferedReader reader = null;
String tempString = null;
int line = 1;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
StringBuffer sb = new StringBuffer(0);
reader = new BufferedReader(new FileReader(file));
while ((tempString = reader.readLine()) != null) {
System.out.println("Line" + line + ":" + tempString);
int start = tempString.indexOf("begin");
int end = tempString.indexOf("end");
if(start > -1){
if(end > -1){
sb.append(tempString.substring(start+"begin".length(), end));
}else{
sb.append(tempString.substring(tempString.indexOf("begin"), tempString.length()));
}
}
if(start > -1 && end == -1){
sb.append(tempString.substring(0, end));
}
line++;
}
System.out.println(sb.toString());
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行结果:
以行为单位读取文件内容,一次读一整行:
Line1:okokokokokokbegin123213okok12412551endokok
123213okok12412551
int startIndex=tempString.lastIndexOf("begin");
int lastIndex=tempString.lastIndexOf("end");
String result=tempString.subString(startIndex,lastIndex);
思路应该是这样的