java如何计算文本文件的行数
import java.io.*;
import java.util.*;
public class Practices {
public static void main(String[] args) throws FileNotFoundException
{
这是我的文本文件:
生存还是毁灭这是
这个问题
现在呢
就这样吧
Scanner input =new Scanner(new File("C:/Users/Charlie/workspace/Summerexercises/src/hamlet.txt"));
int countwords=0;
int countlines=0;
int countchar=0;
while(input.hasNext())
{
String word = input.next();
countwords++;
}
System.out.println("total words= "+ countwords);
这是while循环,它计算行数,但不能正常工作
while(input.hasNextLine())
{
String lines= input.nextLine();
countlines++;
}
System.out.println("total lines= "+ countlines);
input.close();
}
}
# 1 楼答案
**此循环将计算行数**
# 2 楼答案
或者,您可以使用LineNumberReader
资料来源:http://www.technicalkeeda.com/java/how-to-count-total-number-of-lines-of-file-using-java
# 3 楼答案
在第一个循环中,您消耗了所有扫描仪内容,而第二个循环从未执行过。这样做:
# 4 楼答案
你必须重新从文件的开头开始。当第一个循环结束时,您将指向EOF,因此第二个循环中不计算任何行。尝试注释第一个循环并运行此程序