File path or file location for Java - new file()

陌路散爱 提交于 2019-11-28 12:07:30
NINCOMPOOP

If it is already in the classpath and in the same package, use

URL url = getClass().getResource("b.xml");
File file = new File(url.getPath());

OR , read it as an InputStream:

InputStream input = getClass().getResourceAsStream("b.xml");

Inside a static method, you can use

InputStream in = YourClass.class.getResourceAsStream("b.xml");

If your file is not in the same package as the class you are trying to access the file from, then you have to give it relative path starting with '/'.

ex : InputStream input = getClass().getResourceAsStream
           ("/resources/somex.cfg.xml");which is in another jar resource folder
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!