4

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.

donnyton
  • 5,874
  • 9
  • 42
  • 60

2 Answers2

5

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.

Andreas Krueger
  • 1,497
  • 13
  • 16
0

Use instead..

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

That should return true.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Perhaps, but that code was just a demonstration. This still doesn't resolve the issue of creating a file from URL that I can manipulate properly. – donnyton Jul 26 '11 at 00:26