user3474719
user3474719

Reputation: 21

Spaces in Command Line Arguments

I am doing an assignment for university and I have a quick question regarding command line arguments and spaces.

I have to find an image file which will be given to us in the command line. I am trying to run my program but because my file location has spaces in the folder names, java assumes that there is more than one argument.

Therefore when I assign args[0] to the String it stops half way through because of the spaces.

Is there a way to just take everything from the command line and assign it to a String?

Thanks in advance :)

Upvotes: 1

Views: 9079

Answers (3)

Dag
Dag

Reputation: 71

If you select one or more files in File Explorer and run an app from RMB the arguments to app should be the files selected. But if the folder in question contains spaces, you're stuck! No way to add double quotes! Microsoft bug?

Upvotes: 0

vjdhama
vjdhama

Reputation: 5058

The system interprets the space character as a separator for command line arguments. If you want the argument with spaces you would join them with double quotes.

% java test.class "Java is escaped"
Java is escaped

Upvotes: 1

Boris the Spider
Boris the Spider

Reputation: 61128

Just use quotes:

java -jar MyThing.jar "My File Name with loads of spaces.jpg"

Quick demo:

public static void main(final String[] args) throws Exception {   
    Stream.of(args).forEach(System.out::println);
}

Output:

java -jar MyThing.jar My File Name with loads of spaces.jpg
My
File
Name
with
loads
of
spaces.jpg

java -jar MyThing.jar "My File Name with loads of spaces.jpg"
My File Name with loads of spaces.jpg

Upvotes: 10

Related Questions