C盘下新建1.txt
java代码如下:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* 读取文件内容并统计行数
* @author young
*
*/
public class BufferedReaderTest {
public static void main(String[] args) {
BufferedReader br = null;
int line = 0;
String str = null;
try {
br = new BufferedReader(new FileReader("c:\\1.txt"));
while ((str = br.readLine()) != null) {
System.out.println("文件内容: " + str);
++line;
// 读取前4行内容
if(line >= 4){
break;
}
}
// System.out.println("\n文件行数: " + line);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
用正则表达式可能可以,具体网上搜索下第一行到第二行的表达式