I have my program saved in jar format. I need to read data from 2 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?
CodePudding user response:
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.
CodePudding user response:
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.