首页主机资讯​Java获取文件行数的代码怎么写

​Java获取文件行数的代码怎么写

时间2024-01-02 16:04:03发布访客分类主机资讯浏览1263
导读:可以使用LineNumberReader类来获取文件的行数。 import java.io.FileReader; import java.io.LineNumberReader; public class LineCount {...

可以使用LineNumberReader类来获取文件的行数。

import java.io.FileReader;
    
import java.io.LineNumberReader;


public class LineCount {

    public static void main(String[] args) {
    
        String fileName = "path/to/file.txt";
    
        int lineCount = countLines(fileName);
    
        System.out.println("Total number of lines: " + lineCount);

    }


    public static int countLines(String fileName) {

        try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) {
    
            while (reader.skip(Long.MAX_VALUE) >
 0) {

                // Skip to the end of the file
            }
    
            return reader.getLineNumber() + 1;

        }
 catch (Exception e) {
    
            e.printStackTrace();
    
            return -1;

        }

    }

}
    

以上代码定义了一个countLines方法,它接受文件名作为参数,并返回文件的行数。在countLines方法中,我们使用LineNumberReader来读取文件,并使用skip方法跳到文件末尾。然后,我们可以通过调用getLineNumber方法获取当前读取的行数,再加1就得到了文件的行数。如果在读取文件时发生任何异常,我们将打印异常信息并返回-1。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: ​Java获取文件行数的代码怎么写
本文地址: https://pptw.com/jishu/580164.html
mybatis结果集映射的原理是什么 centos7自动重启原因怎么排查

游客 回复需填写必要信息