user1642671
user1642671

Reputation: 85

How to read a file name from cmd that is opening the program?

Currently I have a program that starts and then asks for an command line input to open a file how would I go about it so when the program opens it can take something in that line as a parameter?

So I want to change it so when I start it in command prompt and type

java program
fileName.txt    //program reads it via scanner(System.in)

To

java program fileName.txt  //program runs and takes the fileName.txt

Upvotes: 0

Views: 66

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201507

Unless I'm missing something, you would use this

public static void main(String[] args) {
  String fileName = null;
  if (args.length > 0) {
    fileName = args[0].trim();
  }
  if (fileName != null) {
    // Do something....
  }
}

You can read more here.

Upvotes: 3

Related Questions