john stamos
john stamos

Reputation: 1125

Java - I want to read a file name from command line then use a bufferedreader to read each line

I'm getting an eclipse red underline error on the

 br = new BufferedReader(new FileReader(inFile));

line on "inFile". This is the object that I would like to read which I believe contains the command line filename/path that I give it on the command line. Am I handling this wrong?

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Main {

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

        BufferedReader br = null;

        try {

            String sCurrentLine;

            br = new BufferedReader(new FileReader(inFile));

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }

        } 

        catch (IOException e) {
            e.printStackTrace();
        } 

        finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Upvotes: 2

Views: 63908

Answers (5)

Darrell Teague
Darrell Teague

Reputation: 4282

The variable inFile loses scope outside of the if block:

  if (0 < args.length) {
      File inFile = new File(args[0]);
  }

Change to:

  File inFile = null;
  if (0 < args.length) {
      inFile = new File(args[0]);
      // Make sure the file exists, can read, etc...
  }
  else
  {
    // Do something if a required parameter is not provided...
  }

Upvotes: 1

Stubbs
Stubbs

Reputation: 1

After the 'if' statement block, you could dump contents of "inFile" to a Scanner object.

Scanner scannedIn = new Scanner(inFile);

Then use the '.next' method to verify that you're accessing the file.

System.out.println(scannedIn.next());

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

Change this:

if (0 < args.length) {
    File inFile = new File(args[0]);
}

to this:

File inFile = null;
if (0 < args.length) {
   inFile = new File(args[0]);
} else {
   System.err.println("Invalid arguments count:" + args.length);
   System.exit();
}

because the file variable is not accessible outside the if/else statement.

I've added in the else (for the case when no args are provided) a friendly message saying the the argument count was invalid and exit for the program.

Upvotes: 7

Arthur Dent
Arthur Dent

Reputation: 795

Your variable, inFile, is local to the containing if-block.

Perhaps this:

 public static void main(String[] args) {
      File inFile = null;

      if (0 < args.length) {
          inFile = new File(args[0]);
      }

Upvotes: 1

Andrew W
Andrew W

Reputation: 4618

inFile is declared in the if statement. As such, it's scope ends at line 11;

Upvotes: 1

Related Questions