Java:如何计算没有。文件中的行? [英] Java: How to count the no. of lines in a file?

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

问题描述


可能重复:

用Java编写的文件中的行数

我需要计算通过命令行参数传递给java的txt文件的行数。我知道如何从文件中读取,但我在完成剩下的工作时遇到了麻烦。任何帮助,将不胜感激。
这是我到目前为止:

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);
   }
     }


推荐答案

为什么你在循环中拉 nextInt()并保存 hasNext()?如果你在那里,你已经知道另一条线存在,那么为什么不这样做:

Why are you pulling nextInt() and saving hasNext() inside the loop? If you are in there, you already know another line exists, so why not do something like:

while (file.hasNextLine()) {
  count++;
  file.nextLine();
}

这篇关于Java:如何计算没有。文件中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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