Files, URIs, and URLs conflicting in Java

2019-05-03 15:42发布

问题:

I am getting some strange behavior when trying to convert between Files and URLs, particularly when a file/path has spaces in its name. Is there any safe way to convert between the two?

My program has a file saving functionality where the actual "Save" operation is delegated to an outside library that requires a URL as a parameter. However, I also want the user to be able to pick which file to save to. The issue is that when converting between File and URL (using URI), spaces show up as "%20" and mess up various operations. Consider the following code:

//...user has selected file
File userFile = myFileChooser.getSelectedFile();
URL userURL = userFile.toURI().toURL();

System.out.println(userFile.getPath());
System.out.println(userURL);

File myFile = new File(userURL.getFile());

System.out.println(myFile.equals(userFile);

This will return false (due to the "%20" symbols), and is causing significant issues in my program because Files and URLs are handed off and often operations have to be performed with them (like getting parent/subdirectories). Is there a way to make File/URL handling safe for paths with whitespace?

P.S. Everything works fine if my paths have no spaces in them (and the paths look equal), but that is a user restriction I cannot impose.

回答1:

The problem is that you use URL to construct the second file:

File myFile = new File(userURL.getFile());

If you stick to the URI, you are better off:

URI userURI = userFile.toURI();
URL userURL = userURI.toURL();
...
File myFile = new File(userURI);

or

File myFile = new File( userURL.toURI() );

Both ways worked for me, when testing file names with blanks.



回答2:

Use instead..

System.out.println(myFile.toURI().toURL().equals(userURL);

That should return true.