How to call an XML file when a Java jar file is subtracted

I need to save my XML file in the same place where my Java file is present, and call and use the XML when running the java file. Is there a way this can be achieved?

Below is my code:

File fXmlFile = new File("C:\testing eclipsefolder/workspace/java1`/bin/diliya123/v1.xml"); 

Here I need to specify the path to my XML file. But I do not want to give this path, it should be such that when I transfer my jar file to others, it should not change its path, it should be constant every time.

When I try to run the same script using the code above, I get the following type of error:

 [TestNG] Running: C:\Documents and Settings\saalam\Local Settings\Temp\testng-eclipse-1407458964\testng-customsuite.xml 

Guys, please suggest me how this is possible.

+4
source share
3 answers

Try using a relative path instead of an absolute path, as shown below:

 File fXmlFile = new File("bin/diliya123/v1.xml"); 
+1
source

You mentioned giving your jar file "different". In this case, if the XML file is inserted into the jar, something like this might do what you want
File fXmlFile = new File(getClass().getClassLoader().getResource("YourXmlFile.xml").getFile());

Even if the XML file cannot be added as part of the flag, tell your users to add the location of the XML file in their file system to the CLASSPATH of the calling program, and it should work.

0
source

If you are going to place your jar and xml files in one place ( folder ), you can simply specify the path as follows.

 File xml_file = new File("v1.xml"); 

In my case, my application requires a bunch of xml files. So, I will save all my xml files in a separate directory as xml/ and passing the path as

 File xml_file = new File("xml/v1.xml"); 

Directory structure will be enter image description here Application_folder
enter image description here application.jar
enter image description here> </a> xml <br> v1.xml
"nbsp; =" enter a description of the image here "> v2.xml
"nbsp; =" enter a description of the image here "> v3.xml

When you run jar , it will access the files from the xml folder.

0
source

All Articles