문제

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

도움이 되었습니까?

해결책 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 .....

다른 팁

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").

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top