用Java通过命令行输入文本文件

3
我正在尝试编写一个程序,通过命令行输入文本文件,然后打印出文本文件中单词的数量。我已经花费了大约5个小时的时间。我正在使用Java进行入门课程。
以下是我的代码:
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();
   }    
}

无论我尝试哪种方式,都会出现不同的错误,最常见的是在文件参数中出现“找不到符号”的错误。
input = new Scanner(new File(file));

我仍然不确定java.io和java.nio之间的区别,因此我尝试使用两者中的对象。我相信这是一个很明显的问题,只是我看不到它。我在这里阅读了很多类似的帖子,其中一些代码就是从那里得来的。
我以前编译过程序,但后来在命令提示符中卡住了。
2个回答

2

java.niojava.io 的新版本,都可以用于此任务。我在命令行中测试了以下代码,似乎可以正常工作。"cannot find symbol" 错误信息在 try 块中得到了解决。我认为你之前实例化了一个名为 fileFile 对象两次,这让编译器感到困惑。正如 @dammina 所回答的那样,你需要在 while 循环中添加 input.next(); 以便 Scanner 继续读取下一个单词。

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

}

我明白了。谢谢!我试图实例化文件对象两次,并让我的 while 循环永远运行在文本文件的第一个单词上。 - presence

1
你的代码几乎正确。问题在于,在 while 循环中,您已指定终止条件如下: while (input.hasNext()) // 当还有更多内容可读取时
然而,由于您仅增加计数而不移动到下一个单词,因此计数仅通过始终计算第一个单词来增加。为使其正常工作,只需将 input.next() 添加到循环中以在每次迭代中移至下一个单词即可。
while (input.hasNext()) // while there is more to read
{
total += 1;
input.next();
}

@presence 如果这篇文章对您有帮助,请点个赞,谢谢 :) - dammina

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接