954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Using a scanner to read file from command line

I'm beginning a program that needs to read a file given in the command line. My first question is, if my command line looks like:
$java mysimulator 5 proc.txt
And I want to use proc.txt, which args[i] is it? Right now I'm assuming that the class name is args[0] and so the filename is args[2].

My second question is about an error. At the beginning of my while loop, 'input' is getting an error saying that it is an unknown variable. However, it is defined as a Scanner above in the try catch block. Any ideas?

public class mysimulator {

    
    public static void main(String[] args) {
        //import file from command line
        try {
            Scanner input = new Scanner(new File(args[2]));
        } catch (FileNotFoundException ex) {
            System.out.println("No File Found!");
            return;
        }

       while(input.hasNext()){
           //...
       }
        

    }//end main

}//end mysimulator
boos800
Newbie Poster
5 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

A quick and easy way, when debugging code, to see what is in the args[] array is to print out the Arrays.toString(args) value. It will show you the contents of args.

it is defined as a Scanner above in the try catch block


The variable is defined inside of {} and is not known/is out of scope outside of the {}.
Move the variable definition outside of the {} so it is a inside of same set of {} as any code wanting to use it.

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

thanks! lol its been a while since I've worked with java so I have forgotten trivial things like that.

boos800
Newbie Poster
5 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: