Xxg
Xxg

Reputation: 23

args in '.bat' file contain some spaces, how could I get the args correctly?

Stat command in cmd:

start.bat -arg1 -ar g2 -arg3

How can I get the second arg? The string 'ar g2' contain one space .

I need get the args(may contain space character) from bat file, then I will handle them in the java file.

Could anybody give me a solution? Thanks very much.

Upvotes: 1

Views: 217

Answers (3)

frIT
frIT

Reputation: 3305

On the (DOS/Windows) command line, you should always surround arguments that contain spaces, with quotes. E.g.

start.bat -arg1 "-ar g2" -arg3

Surrounding each and every argument with quotes, even ones without spaces, will not hurt, but your batch script needs to remove the quotes then (see code samples below).

This has been the case for as long as I can remember (pre-Windows 3.1 DOS days). When long filenames (which could include spaces) were implemented, this became more common. E.g.

C:\Users\adam>copy "My Documents" "My Backup Files"

(try it without quotes too).

This is the CMD way, and any programs called from the CMD will understand this correctly.

Code Samples (may be useful for debugging, to see what actually is returned. Run the Batch file or Java class with a list of arguments and play around.)

Batch script (the ~ (tilde) character is the important thing, it removes the surrounding quotes):


    @echo off
    FOR %%a IN (%*) DO echo [%%~a]

Java (surrounding quotes automatically removed)


    public class TestArg {
        public static void main(String[] args) {
            for (String a : args) {
                System.out.println("[" + a + "]");
            }
        }
    }

Upvotes: 3

Tschallacka
Tschallacka

Reputation: 28742

You could use something like below... just proof of concept code, the rest you'll need to do yourself... or buy a book on java programming like I did.

public static void main(String argv[])
    {
    String argument1 = "";
    String argument2 = "";
    String argument2value = "";
    String argument3 = "";
    for(int c=0;c<argv.length;c++)
        {
        if(argv[c].indexOf("-")==0)
            {
            if(argument1.length() == 0)
                {
                argument1 = argv[c].substring(1,argv[c].length());
                }
            if(argument2.length() == 0)
                {
                argument2 = argv[c].substring(1,argv[c].length());
                }  
            }
        else
            {
            if(argument2.length() != 0)
                {
                argument2value = argument2value + argv[c]
                }
            }
        }
    }

Upvotes: 0

frG
frG

Reputation: 23

Isnt it possible to split the string with | character, and then trim the values (left + right) ? This should preserve the spaces inbetween.

Upvotes: 0

Related Questions