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

我是研究僧i 提交于 2019-12-25 02:16:12

问题


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 ;)


回答1:


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));



回答2:


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()



来源:https://stackoverflow.com/questions/8417056/how-to-get-a-proper-folder-handle-from-a-uri-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!