java怎么读取txt文件的行数

Python013

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

    }

}

可以通过BufferedReader 流的形式进行读取,之后循环输出每一行的内容。

BufferedReader bre = null

try {

bre = new BufferedReader(new FileReader(file))//file为文件的路径+文件名称+文件后缀

while ((str = bre.readLine())!= null) // ●判断最后一行不存在,为空结束循环

{

System.out.println(str)//原样输出读到的内容

};

备注: 流用完之后必须close掉,如上面的就应该是:bre.close()

int rows = 0

double total = 0.00

Scanner sc = new Scanner(new File("D:/data.txt"))

while(sc.hasNext()){

    String str = sc.next()

    if(rows % 2 != 0){

        double num = Double.parseDouble(str)

total += num

    }

    rows++

}

System.out.println("和: "+total)

System.out.println("行: "+rows/2)

System.out.println("平均:"+total*2/rows)