如何以有效的方式获取文件中的行数? [英] How can I get the count of line in a file in an efficient way?

查看:123
本文介绍了如何以有效的方式获取文件中的行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大文件。它包括大约3.000-20.000行。如何使用Java获取文件中的行总数?

I have a big file. It includes approximately 3.000-20.000 lines. How can I get the total count of lines in the file using Java?

推荐答案

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
int lines = 0;
while (reader.readLine() != null) lines++;
reader.close();

更新:为了回答此处提出的性能问题,我做了一个测量。第一件事:20.000行太少,以使程序运行一段时间。我创建了一个包含500万行的文本文件。这个解决方案(从没有像-server或-XX-options这样的参数的java开始)在我的盒子上需要大约11秒。与 wc -l <​​/ code>(UNIX命令行工具计数行)相同,为11秒。读取每个字符并寻找'\ n'的解决方案需要104秒,9-10倍。

Update: To answer the performance-question raised here, I made a measurement. First thing: 20.000 lines are too few, to get the program running for a noticeable time. I created a text-file with 5 million lines. This solution (started with java without parameters like -server or -XX-options) needed around 11 seconds on my box. The same with wc -l (UNIX command-line-tool to count lines), 11 seconds. The solution reading every single character and looking for '\n' needed 104 seconds, 9-10 times as much.

这篇关于如何以有效的方式获取文件中的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆