0

I have an application that receives a path as a command line argument. The path can contain spaces, so it can be sended with quotes. I need to verify if this path is correct, so I execute 'exists' method from 'File' class:

public static void main (String... args) {
  System.out.println("arg=" + args[0]);
  File f = new File(args[0]);
  System.out.println("exists=" + f.exists());
}

When I run the application with the follow arguments, I obtain this results (assume that "c:\folder" exists). Pay attention with final slash and quotes:

> java Test c:\folder
args=c:\folder
exists=true

> java Test c:\folder\
args=c:\folder\
exists=true

> java Test "c:\folder"
args=c:\folder
exists=true

> java Test "c:\folder\"
args=c:\folder
exists=false

I don't understand what's happens with last example. First in args result don't print final slash and then File class say that path doesn't exists. Second example without quotes works well. Argument path has a free user edition, so it's possible that can include quotes (if path has folder with spaces) and a final slash.

3
  • 5
    \" is an escaped ". Research character escaping. Commented Oct 28, 2016 at 16:07
  • did you manage to fix the problem? Commented Oct 28, 2016 at 16:20
  • It seems that talex solution works, but two slashes at the end It's a bit ugly. Anyway I haven't found any better way to deal with this. Commented Oct 31, 2016 at 8:35

1 Answer 1

2

It is not java issue but your shell. \ act as escape character if it is used before " in Windows. To work around that you can write parameter as "c:\folder\\"

It is also strange output. When i did the same I got args=c:\folder" in last case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.