在 java 中通过命令行输入文本文件

Input a text file through command line in java

我正在尝试编写一个程序,通过命令行输入一个文本文件,然后打印出文本文件中的字数。我已经在这上面花了大约 5 个小时。我正在使用 java.

进行介绍 class

这是我的代码:

import java.util.*;
import java.io.*;
import java.nio.*;

public class WordCounter
{
    private static Scanner input;

    public static void main(String[] args)
    {
        if (0 < args.length) {
        String filename = args[0];
        File file = new File(filename);
        }

    openFile();
    readRecords();
    closeFile();
    }

    public static void openFile()
   {
      try
      {
         input = new Scanner(new File(file)); 
      } 
      catch (IOException ioException)
      {
         System.err.println("Cannot open file.");
         System.exit(1);
      } 
  }

    public static void readRecords()
   {
        int total = 0;
        while (input.hasNext()) // while there is more to read
            {
                total += 1;
            }
        System.out.printf("The total number of word without duplication is: %d", total);
     }

    public static void closeFile()
   {
      if (input != null)
         input.close();
   }    
}

我尝试过的每一种方法都得到了不同的错误,最一致的错误是 "cannot find symbol"

中的文件参数
input = new Scanner(new File(file));

我仍然不完全确定 java.io 和 java.nio 之间的区别是什么,所以我尝试使用两者的对象。我确定这是一个明显的问题,我只是看不到它。我在这里阅读了很多类似的帖子,这就是我的一些代码的来源。

我之前已经编译过程序,但它在命令提示符下冻结了。

您的代码几乎是正确的。事情是在 while 循环中你指定了如下终止条件,

while (input.hasNext()) // 还有更多内容需要阅读

然而,由于您只是增加计数而不移动到下一个单词,因此计数只是通过始终计算第一个单词而增加。要使其工作,只需将 input.next() 添加到循环中以在每次迭代中移动到下一个单词。

while (input.hasNext()) // while there is more to read
{
total += 1;
input.next();
}

java.niojava.io 的新改进版本。您可以将其中任何一个用于此任务。我在命令行中测试了以下代码,它似乎工作正常。 "cannot find symbol" 错误消息在 try 块中得到解决。我认为您通过实例化名为 fileFile 对象两次来混淆编译器。正如@dammina 回答的那样,您确实需要将 input.next(); 添加到 while 循环中,以便扫描程序继续下一个单词。

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class WordCounter {

    private static Scanner input;

    public static void main(String[] args) {

        if(args.length == 0) {
            System.out.println("File name not specified.");
            System.exit(1);
        }

        try {
            File file = new File(args[0]);
            input = new Scanner(file);
        } catch (IOException ioException) {
            System.err.println("Cannot open file.");
            System.exit(1);
        }

        int total = 0;
        while (input.hasNext()) {
            total += 1;
            input.next();
        }

        System.out.printf("The total number of words without duplication is: %d", total);

        input.close();
    }

}