java中怎么获得一个文本文件的行数

来源:百度知道 编辑:UC知道 时间:2024/05/17 02:29:28
比如说有一个名为name.txt的文件,我想要获得它的行数,怎么做?具体的代码是什么?各位高手帮帮忙吧!

涉及到java中读写文件的IO操作。
获取一个文本文件的行数较为方便的方法,是通过BufferedReader类的readLine()方法,间接的统计行数。
源代码:
public static int getTextLines() throws IOException {
String path = "c:\\job.txt" ;// 定义文件路径
FileReader fr = new FileReader(path); //这里定义一个字符流的输入流的节点流,用于读取文件(一个字符一个字符的读取)
BufferedReader br = new BufferedReader(fr); // 在定义好的流基础上套接一个处理流,用于更加效率的读取文件(一行一行的读取)
int x = 0; // 用于统计行数,从0开始
while(br.readLine() != null) { // readLine()方法是按行读的,返回值是这行的内容
x++; // 每读一行,则变量x累加1
}
return x; //返回总的行数
}

一行一行的读,每读一行统计一次。
int count = 0;
File f = new File("你的文件");
InputStream input = new FileInputStream(f);

BufferedReader b = new BufferedReader(new InputStreamReader(input));

String value = b.readLine();
if(value != null)

while(value !=null){
count++;
value = b.readLine();
}

b.close;
input.close;