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

橙三吉。 提交于 2019-11-27 06:04:16

问题


I have the following structure for my project.

In Eclipse:

myPorjectName
  src
    com.example.myproject
        a.java
    com.example.myproject.data
        b.xml

In a.java, I want to read b.xml file. How can I do that? Specifically, in a.java, I used the following code:

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("data/b.xml"));

This code cannot find b.xml. However, if I change the path to src/com/example/myproject/data/b.xml then it works. The current location seems to be in the root of my project file.

But I see other people's examples, if b.xml and a.java are in the same folder, then we can directly use new File("b.xml"). But I try putting b.xml in the same folder of a.java rather than putting in the sub folder, but it still does not work. If this works, then in my case, I should be able to use new File("data/b.xml"), right? I really do not understand why this is not working.


回答1:


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


来源:https://stackoverflow.com/questions/16313260/file-path-or-file-location-for-java-new-file

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