java怎么读取txt文件的行数

Python08

java怎么读取txt文件的行数,第1张

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)//输出文件行数