Java 打印出文件包含的行数

Java 打印出文件包含的行数,java,Java,目前,当我输入一个有效的.txt文件时,我的代码什么也不做。我想打印文件包含的行数。谁能告诉我为什么现在什么都没有发生 public class Task3 { public static void main(String[] args) throws FileNotFoundException { // instance variables int characterCount = 0; int wordCount = 0;

目前,当我输入一个有效的.txt文件时,我的代码什么也不做。我想打印文件包含的行数。谁能告诉我为什么现在什么都没有发生

public class Task3
{
    public static void main(String[] args) throws FileNotFoundException
    {
        // instance variables
        int characterCount = 0;
        int wordCount = 0;
        int lineCount = 0;
        // create a Scanner object to read in file name from console input
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter the file name: ");
        String filename = in.next();
        File inputFile = new File(filename);


        // create a Scanner object to read the actual text file
        Scanner inFile = new Scanner(inputFile);

        int lines = 0;

        while (inFile.hasNextLine())
        { // enter while loop if there is a complete line available
        in.nextLine();
            lines++;
            // increase line counter variable
            }
          System.out.println(lines); 
更改:

in.nextLine();
致:


您不是从文件中读取行,而是从标准输入中读取行。

在此循环中:

    while (inFile.hasNextLine())
    { // enter while loop if there is a complete line available
        in.nextLine();
        lines++;
        // increase line counter variable
    }
您正在使用
系统的扫描仪。在
中,不是为文件创建的扫描仪。因此,对
nextLine
的调用将等待您的输入,而不是转到文件中的下一行。这就是为什么看起来什么都没发生

将.nextLine中的
替换为
infle.nextLine
,它将起作用。

添加一个System.out.println(inputFile.exists())以查看您没有创建新文件

    while (inFile.hasNextLine())
    { // enter while loop if there is a complete line available
        in.nextLine();
        lines++;
        // increase line counter variable
    }