-1

I have my program saved in JAR format. I need to read data from two different files given by user using this line: java -jar app.jar file1.txt file2.txt. How can I read it? I wrote this:

Scanner scan = new Scanner(System.in);
String inputFileName1 = scan.next().trim();
String inputFileName2 = scan.next().trim();
File input1 = new File(inputFileName1);
Scanner file1 = new Scanner(input1);
File input2 = new File(inputFileName2);
Scanner file2 = new Scanner(input2);

It works when I manually write: file1.txt file2.txt, but not with the command line. What's wrong?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
anna
  • 1
  • 3
  • You should use the `args` array in your `main` method to get command line arguments `public static void main(String[] args)`. – Mushroomator Apr 24 '22 at 19:53
  • Does this answer your question? [Passing on command line arguments to runnable JAR](https://stackoverflow.com/questions/8123058/passing-on-command-line-arguments-to-runnable-jar) – Mushroomator Apr 24 '22 at 19:54

2 Answers2

2

When you use command line to send the arguments, you can use args to access those arguments. For example, if you run java yourfile arg0 arg1 on the command line, then you can access arg0 and arg1 by using args[0] respectively args[1] in your code.

So, if you use

public static void main(String[] args) {
    File input1 = new File(args[0]);
    Scanner file1 = new Scanner(input1);
    File input2 = new File(inputFileName2);
    Scanner file2 = new Scanner(args[1]);
    ...
}

then your code should work fine.

Queeg
  • 7,748
  • 1
  • 16
  • 42
Jhanzaib Humayun
  • 1,193
  • 1
  • 4
  • 10
0

You can get the arguments from the command line through the args from your main method.

Giving the args out would look something like this:

public static void main(String[] args) {
  for (int i = 0; i < args.length; i++) {
    System.out.println(args[i]);
  }
}

You could make something like File input1 = new File(args[0]); to get the first argument.