Java:如何计算数量。文件中的行数?
可能的重复:
Java 文件中的行数
我需要计算通过命令行参数传递给 java 的 txt 文件的行数。我知道如何从文件中读取内容,但我在完成其余的事情时遇到了困难。任何帮助将不胜感激。 这是我到目前为止所拥有的:
import java.util.*;
import java.io.*;
public class LineCounter {
public static void main (String [] args) throws IOException{
Scanner file = new Scanner(new File("myFlile.txt"));
int count = 0;
while(file.hasNext()){
boolean s = file.hasNext();
int count = file.nextInt();
}
System.out.println(count);
}
}
Possible Duplicate:
Number of lines in a file in Java
I need to count the number of lines of a txt file that is passed to java through a command line argument. I know how to read from a file but i am having trouble doing the rest. any help would be appreciated.
here is what i have so far:
import java.util.*;
import java.io.*;
public class LineCounter {
public static void main (String [] args) throws IOException{
Scanner file = new Scanner(new File("myFlile.txt"));
int count = 0;
while(file.hasNext()){
boolean s = file.hasNext();
int count = file.nextInt();
}
System.out.println(count);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为什么要在循环内拉动
nextInt()
并保存hasNext()
?如果您在那里,您已经知道存在另一条线,那么为什么不执行以下操作:Why are you pulling
nextInt()
and savinghasNext()
inside the loop? If you are in there, you already know another line exists, so why not do something like:您应该检查 javadoc 中的 java.util.Scanner 类: http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
扫描程序具有可用于此目的的方法 hasNextLine 和 nextLine。 hasNextLine() 检查文件中是否还有行,nextLine() 从文件中读取一行。使用这些方法,你会得到这样的算法:
你的代码可能是这样的
You should check javadoc for the java.util.Scanner class: http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
Scanner has methods hasNextLine and nextLine that you can use for this. hasNextLine() checks if there are still lines in the files and nextLine() reads one line from the file. Using those methods you get an algorithm like this:
Your code could be something like this
你可以这样做:
You can do it this way:
不久前,我写了一个小型项目分析器。这并不是一个真正的答案,但我想分享我的解决方案。目前还没有
main()
方法。只需创建一个这样的:它支持根据文件扩展名过滤文件。因此您可以指定例如 C++。这将接受所有
.h
和.cpp
文件。您必须指定一个文件夹,它将递归地计算文件、行和字节数。
I wrote a little project analyser, some time ago. It's not really an answer, but I wanted to share my solution. There is no
main()
method yet. Just create one like this:It supports for filtering files on file extensions. So you can specify for example C++. This will accept all
.h
and.cpp
files.You have to specify a folder and it will recursively count files, lines and bytes.
您可以使用
BufferedReader
< /a> 读取完整行或LineNumberReader
本身进行计数。You can use a
BufferedReader
to read complete lines or aLineNumberReader
which does the counting itself.