Home > Blockchain >  Java - read args with "*"
Java - read args with "*"

Time:12-26

I need to make program, that gets optional arguments from command line. In case there shows flag -regex i need to read folowing regex expression and save it to program as a string. Something like: java Main -regex *.java

What I have now looks like:

public static void main(String[] args) 
...
if (args[i].equals("-regex")) {
   String myRegex = args[i 1];
   System.out.println(myRegex);
   i  ;
   i  ;

}
...

But, as I run program from folder, where are some files as file1.java and file2.java, the program prints "file1.java". What can i do to get my variable with "*.java"?

When I tried to print all the args, with:

for (String arg:args) {
    System.out.println(arg);
}

it gives me:

-regex
file1.java
file2.java

Which leads me to conclusion, that I need to read the args differently...

CodePudding user response:

In Java, use string.compareTo(string) to compare strings instead of the ==-operator:

    package com.main;
    
    public class Main {
        public static void main(String[] args) {
            if (args[0].compareTo("-regex") == 0) {
                String myRegex = args[1];
                System.out.println(myRegex);
            }
        }
    }

CodePudding user response:

Things could be probably solved, if I run the program from the folder, where couldn't be any matching patterns. But I seek for more universal solution.

CodePudding user response:

You need to escape asterisk for the shell / terminal you use, as the shell is performing file name expansion before running the java application. For bash you can use backslash, this should pass *.file as args[1]:

java -cp your.jar your.Main -regex \*.file

Using quote also works to escape the default file expansion in some shells, and fixes when using Windows CMD.EXE:

java -cp your.jar your.Main -regex "*.file"

CodePudding user response:

You will need to enclose the Command Line command double (") quotation marks, for example:

java Main "-regex *.java"

then use something like this:

String myRegex = "";
for (int i = 0; i < args.length; i  ) {
    if (args[i].startsWith("-regex")) {
        String[] commandParts = args[i].split("\\s ");
        if (commandParts.length > 1) {
            myRegex = commandParts[1];
            System.out.println(myRegex);
        }
    }
} 

The console will display *.java when the application starts.

  • Related