Michael
Michael

Reputation: 715

How to get a proper folder handle from a URI in Java?

I noticed a little issue. What my application gets is a URI of a file e.g. file:///C:/temp/somefolder/somedocument.txt as a String.

What my application has to do is check the folder for more files and process them. To do that, I'd normally do something like

File file = new File(myURI);
File folder = file.getParentFile();
File[] peers = folder.getParentFile().listFiles();

Unfotunately, this doesn't seem to work at all when you use URI's. .listFiles always returns null, even if I open a File() handle to the URI of the folder.

Any ideas how to get around this problem?

P.S.: none of the methods of File or java.net.URI will return an absolute path which is not a URI ;)

Upvotes: 0

Views: 3981

Answers (2)

Alejandro Diaz
Alejandro Diaz

Reputation: 431

Try:

File file = new File(myURI);
File[] peers = new File(file.getParent()).listFiles();

This worked for me. However if I use your code I get a NPE when I call getParentFile()

Upvotes: 0

ptomli
ptomli

Reputation: 11818

Your myURI is actually a String representation of a URI. The constructor of File that you're calling is

public File(String pathname)

Note the pathname bit, it's not a URI-ish value.

Try

File file = new File(new URI(myURI));

Upvotes: 1

Related Questions