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

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 the b.xml file. How can i do this? In particular, 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 will work. The current location seems to be at the root of my project file.

But I see examples of other people, if b.xml and a.java are in the same folder, then we can directly use new File("b.xml") . But I try to put b.xml in the same a.java folder instead of putting it in a subfolder, but it still does not work . If this works, then in my case I have to use new File("data/b.xml") , right? I really don't understand why this is not working.

+7
source share
1 answer

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 the static method, you can use

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

If your file is not in the same package as the class with which you are trying to access the file, then you must specify its relative path, starting with '/' .

 ex : InputStream input = getClass().getResourceAsStream ("/resources/somex.cfg.xml");which is in another jar resource folder 
+17
source

All Articles