2014-01-18 74 views
0

我正在尝试读取下面的类中的xml配置。它运行时运行它。但是当我将它导出到Runnable Jar.The文件不被读取..? ?如何使用getResourceAsStream读取XML文件

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))); 
         } 
      } 

我GOOGLE了&发现的getResourceAsStream method.But似乎抛出FileNotFoundException异常。 &我不知道如何在我的代码中添加InputSream?

所以帮我在正确的方向:)

感谢您的帮助......

注意 我试过的方法进行了报道

+0

你加罐子类路径? – lakshman

+0

看看[这](https://stackoverflow.com/questions/20963531/why-do-i-need-to-include-classloader-getsystemresourcesasstream-when-parsing-a/20963663#20963663),它可以帮助你。 –

回答

0

Atlast找到如何使用getResourceAsStream .The下面行不魔术

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

Thankz所有的答案.....

0

但似乎扔FileNotFoundException

最可能的原因是路径ame到文件是不正确的。

您似乎使用"res/config.xml"作为路径名。这是一个相对路径名,相对路径名是相对于当前目录;例如您尝试启动JAR时的目录。 (请注意,如果使用“/”或“\”作为路径分隔符,则无关紧要。无论运行时平台如何,Java的用于打开文件的内置类都可以应对任何一种形式。 )

+0

如果路径错误。那么当我运行时它是如何工作的? – AruLNadhaN

+0

由于当前目录不同。你知道“当前目录”实际上是什么意思吗? –

+0

查看图片。编辑代码并发帖。我无法收到你...请问 – AruLNadhaN

0

从classpath中读取 - 在配置路径方面非常灵活。这里是:How to really read text file from classpath in Java

顺便说一句,以避免更换反斜杠和斜线在Win和Unix上运行使用File.separator。例如:"res" + File.separator + "config.xml"。您也可以使用new File("res", "config.xml")

+0

运行它时正在工作。但是当我将其导出到可运行Jar中时。 – AruLNadhaN

+0

当你运行你的jar时检查你的classpath。它是'java -cp'或'-classpath'参数。它应该有罐子。 –