java读取文本文件后怎样算出文本文件的行数

Python013

java读取文本文件后怎样算出文本文件的行数,第1张

获取行数涉及到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 //返回总的行数

}

相信看完上面的,应该就会了。

import java.io.File

import java.io.RandomAccessFile

/**

 * 读取文档的第二行内容

 *

 * @author 3306 2017年3月21日

 * @see

 * @since 1.0

 */

public class CountLine {

    /*

     * 读取文件绝对路径

     */

    private static String filePath = "d:/cms.sql"

    public static void main(String[] args) {

        long line = readLine(filePath)

        System.out.println(line)

    }

    /**

     * 读取文件行数

     * 

     * @param path

     *            文件路径

     * @return long

     */

    public static long readLine(String path) {

        long index = 0

        try {

            RandomAccessFile file = new RandomAccessFile(new File(path), "r")

            while (null != file.readLine()) {

                index++

            }

            file.close()

        } catch (Exception e) {

            e.printStackTrace()

        }

        return index

    }

}

java IO流操作中,是不能直接通过API得到的,需要遍历这个文件然后统计出来行数,当每读一行的时候,就让变量的值加一,如下代码:

BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt"))

String line = ""

int lineCount = 0

while((line = br.readLine()) != null)

{

lineCount++//计数器,统计行数

}

System.out.println("LineCount = " + lineCount)//输出文件行数