Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getPath() and Spaces in Java

Tags:

java

file

I encountered a problem with getPath() recently.

my code looks something like this:

File path = new File(Main.class.getResource("/worlds/").getPath());
File[] files = path.listFiles();

The Problem now is, that if there is a space somewhere in the Path to the Main class, path.listFiles() will return null. If there is no Space, everything works fine.

if i print the path to the cmd, i see that every space is replaced by an %20

like image 571
Simiil Avatar asked Oct 08 '11 21:10

Simiil


2 Answers

that is not the correct way to convert a URL to a File. try this instead:

new File(Main.class.getResource("/worlds/").toURI());
like image 171
jtahlborn Avatar answered Oct 19 '22 11:10

jtahlborn


Don't do that. A resource URL returned by getResource() isn't necessarily a file on the file system, which is what File represents.

like image 3
Ryan Stewart Avatar answered Oct 19 '22 12:10

Ryan Stewart