I have a simple project which depends on jar file. Jar file has single class with constructor which takes in path to props.xml.
This is the project structure:
Here is the main class:
import com.file.reader.FileReader; public class SimpleExample { public static void main(String[]args){ FileReader rd = new FileReader("props.xml"); } } Here is the FileReader.java
package com.file.reader; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; public class FileReader { public FileReader(String fileName){ try { File file = new File(fileName); DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document doc = dBuilder.parse(file); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); if (doc.hasChildNodes()) { System.err.println((doc.getChildNodes())); } } catch (Exception e) { System.out.println(e.getMessage()); } } } This basically reads the xml file.
FileReader.java is a jar file being accessed in my project. When i run in eclipse i see the below output:
[#document: null] Root element :company But when i exported the DummyFilePath as jar file and tried running from command line.
I see that error is being thrown:
C:\Users\javaMan\props.xml (The system cannot find the file specified) From Command line I am running
Java -jar DummyFilePath.jar How can i make it run through command line
EDIT
After checking some linked questions i tried a different way:
I moved the props.xml to src folder.
Then i changed the SimpleExample.java as below:
import java.io.File; import java.net.URL; import com.file.reader.FileReader; public class SimpleExample { public static void main(String[] args) { SimpleExample se = new SimpleExample(); System.err.println(se.getPath()); FileReader rd = new FileReader(se.getPath()); } public String getPath(){ URL url1 = getClass().getClassLoader().getResource("props.xml"); File f = new File(url1.getFile()); return f.getAbsolutePath(); } } So when i run in eclipse i see the below which is good:
C:\Users\javaMan\Perforce\DummyFilePath\bin\props.xml [#document: null] Root element :company When i run the same DummyFilePath.jar i see the below error:
C:\Users\javaMan\Desktop>java -jar "C:\Users\javaMan\Desktop\DummyFilePath.jar" C:\Users\javaMan\Desktop\file:\C:\Users\javaMan\Desktop\DummyFilePath.jar!\props.xml C:\Users\javaMan\Desktop\file:\C:\Users\javaMan\Desktop\DummyFilePath.jar!\props.xml (The filename, directory name, or volume label syntax is incorrect)