计算文件的行数

Count the lines of a file

我有一个关于 Java 的问题:

我正在尝试制作一个遍历文件并检查某些内容的程序,但为此我需要一些东西来计算行数,有人知道这样做的好方法吗?

我以前从未使用过文件,所以我不太了解。 我也没有代码可以展示,因为我不知道该怎么做。

你自己在网上搜索一下就可以找到了。 但是,这里是我使用的代码:

    public static int countLines(String filename) throws IOException {
        InputStream is = new BufferedInputStream(new FileInputStream(filename));
        try {
            byte[] c = new byte[1024];
            int count = 0;
            int readChars = 0;
            boolean empty = true;
            while ((readChars = is.read(c)) != -1) {
                empty = false;
                for (int i = 0; i < readChars; ++i) {
                    if (c[i] == '\n') {
                        ++count;
                    }
                }
            }
            return (count == 0 && !empty) ? 1 : count;
        } 
        finally {
            is.close();
        }
    }

希望对你有用。

更新:

这对你来说应该更容易。

BufferedReader reader = new BufferedReader(new FileReader(file));
int lines = 0;
while (reader.readLine() != null) lines++;
reader.close();
System.out.println(lines);

你可以试试这个,在 lines 变量中你会得到行数。

 public String getFileStream(final String inputFile) {
            int lines = 0;
            Scanner s = null;

            try {
                s = new Scanner(new BufferedReader(new FileReader(inputFile)));
                while (s.hasNext()) {
                   lines++;
                }
            } catch (final IOException ex) {
                ex.printStackTrace();
            } finally {
                if (s != null) {
                    s.close();
                }
            }
            return result;
    }

在Java 8:

long lineCount = 0;

try (Stream<String> lines = Files.lines(Paths.get(filename))){
    lineCount = lines.count();
} catch (final IOException i) {
    // Handle exception.
}

你可以简单地做到这一点:-

        BufferedReader br = new BufferedReader(new FileReader(FILEPATH));
        int lineCount = 0;
        while(br.readLine() != null)
            lineCount++;
        System.out.println(lineCount);

BufferedReader class 提供 readLine() 逐行读取文本,因此可用于获取行数。

你可以简单地做:

public static void main(String[] args) {

    int linecount = 0;

    try {
        // Open the file
        FileInputStream fstream = new FileInputStream("d:\data.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(
                fstream));
        String strLine;
        // Read File Line By Line
        while ((strLine = br.readLine()) != null) {
            if (strLine.trim().length() > 0) { // check for blank line
                linecount++;
            } else {
                continue;
            }
        }

        System.out.println("Total no. of lines = " + linecount);
        // Close the input stream
        br.close();
    } catch (Exception e) {
        // TODO: handle exception
    }

}