利用java,想要获取一段文字所在行下几行的文字,怎么做啊

利用java,加入在txt中的一行有这样一段文字“今天天气不错”,我想要获取到它所在行的下几行,怎么办啊?

假设你已经将文件读取到内存中,并保存在String str变量中,那么你可以这么做:
String[] result=str.split("\n");//将内容按换行符打散,这样数组中的每一个元素就是一行文字
for (int i=0; i<result.length; i++) {
..........

//在这个循环里,你可以找到“今天天气不错”在哪一行,记录它,假设你记录在变量int k中,现在,你想读k行以下的所有行,或者你想读k行以后的某一行不是很容易就可以读到了?
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-07-07
利用正则表达式 进行筛选啊 或者自己判断
进行字符串的过滤啊。
第2个回答  2012-07-07
学得有点久了,具体的代码一时还拿不出来,思想是设标识符boolean is=false;读文件的时候是一行一行的读,每读一行的时候都用contains方法,看看那一句是否包含所说内容,如果包含就让is=true,然后再读以后行的时候,把封装的流写出去。
第3个回答  推荐于2017-09-18
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
*
* @author Administrator
*/
public class NewClass {
public static void main(String[] a) {
String[] strs = new NewClass().readFileByLine("C:/temp.txt", "aaa", 3);//得到
C:/temp.txt中内容为aaa行后的3行内容

for (int i = 0; i < 3; i++) {
System.out.println(strs[i]);
}
}
public String[] readFileByLine(String fileName, String findLine, int rows) {
File file = new File(fileName);
BufferedReader reader = null;
String[] ret = new String[rows];
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
if (tempString.equals(findLine)) {
break;
}
}
int n = 0;
while ((tempString =
reader.readLine()) != null && n < rows) {
ret[n] = tempString;
n++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return ret;
}
}本回答被提问者采纳
相似回答