java怎么读取txt文件的行数

2025-02-26 23:43:09
推荐回答(1个)
回答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;
    }

}