presence presence - 6 days ago 6
Java Question

Input a text file through command line in java

I am trying to write a program that inputs a text file through the command line and then prints out the number of words in the text file. I've spent around 5 hours on this already. I'm taking an intro class using java.

Here is my code:

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


Each way I've tried I get a different error and the most consistent one is "cannot find symbol" for the file argument in

input = new Scanner(new File(file));


I'm also still not entirely sure what the difference between java.io and java.nio is so I have tried using objects from both. I'm sure this is an obvious problem I just can't see it. I've read a lot of similar posts on here and that is where some of my code is from.

I've gotten the program to compile before but then it freezes in command prompt.

PEF PEF
Answer

java.nio is the New and improved version of java.io. You can use either for this task. I tested the following code in the command line and it seems to work fine. The "cannot find symbol" error message is resolved in the try block. I think you were confusing the compiler by instantiating a File object named file twice. As @dammina answered, you do need to add the input.next(); to the while loop for the Scanner to proceed to the next word.

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

}
Comments