user2450099
user2450099

Reputation: 385

Java - taking multiple paths as command line arguments whitespace issue

Let's say I want to pass the following paths on the command line:

Path a: C:\example a\test
Path b: C:\example b\test\

java -jar myjar.jar C:\example a\test C:\example b\test\

Java splits arguments using whitespace, so we would end up with an args array like this:

arr[0] = C:\example
arr[1] = a\test
arr[2] = C:\example
arr[3] = b\test\

But if we also want to accept non-absolute paths, so supplying "\test" will cause the program to accept that as <parent directory>\test.

This gives a lot of problems and is much more complicated than it first appears. How do we tell Java that "a\test" is actually a part of "C:\example a\test" rather than "<parent directory>\a\test"?

Upvotes: 0

Views: 1436

Answers (2)

iPouf
iPouf

Reputation: 93

Use quotes:

java -jar myjar.jar "C:\example a\test" "C:\example b\test\"

Upvotes: 1

Trinimon
Trinimon

Reputation: 13957

Create a canonical file and extract the absolute name from it:

try {
    File file = (new File(arr[0])).getCanonicalFile();
    arr[0] = file.getAbsolutePath();

} catch (IOException e) {
    // handle exception
}

This way you can compare them.

Upvotes: 0

Related Questions