Question

I am trying to read an xml configuration in the below class.It is Working when Running It .But When i Export it into a Runnable Jar.The file is not being read ..??

 public KeyTranslator() {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                String sPath = "res/config.xml";



     //InputStream is = (InputStream) Thread.currentThread().getContextClassLoader().getResourceAsStream(sPath);
    //InputStream is = this.getClass().getResourceAsStream((sPath);

                try {
                        DocumentBuilder builder = factory.newDocumentBuilder();
                        if (AppFrame.jar == null) {
                                this.myDoc = builder.parse( new File((AppFrame.basePath+sPath).replace('\\', '/')) );//ensure seperator is '/' as linux is picky
                        } else {
                                this.myDoc = builder.parse(AppFrame.jar.getInputStream(AppFrame.jar.getJarEntry(sPath)));
                        }
            }

I googled & found the getResourceAsStream method.But it seems to throw FileNotFoundException.& i Don't know how to add InputSream in my Code ???

So Help me in the Right Direction :)

Thanks for your Help ...

Note The Method i Tried has been Commented

Was it helpful?

Solution 3

Atlast Found how to use getResourceAsStream.The Below line does the Magic

this.myDoc = builder.parse((getClass().getResourceAsStream("/xml/config.xml")));

Thankz for all the Answers .....

OTHER TIPS

But it seems to throw FileNotFoundException

The most likely reason is that the pathname to the file is incorrect.

You seem to be using "res/config.xml" as your pathname. That is a relative pathname, and relative pathnames are resolved relative the current directory; e.g. the directory where you were when you tried to launch the JAR.

(Note that it doesn't actually matter if you use "/" or "\" as the path separator. Java's built-in classes for opening files can cope with either form, irrespective of the runtime platform ...)

Read it from classpath - makes it very flexible in terms of configuring path. Here is how: How to really read text file from classpath in Java.

BTW to avoid replacing backslashes and slashes to run on Win and Unix use File.separator. For instance: "res" + File.separator + "config.xml". You can also use new File("res", "config.xml").

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top