簡體   English   中英

為什么xml文件不能與可執行文件一起使用

[英]why xml file is no working with executable le jar

我的eclipse項目中有server.XML文件,從eclipse執行時,它工作正常。

但是當我使用package all files選項創建可執行jar時,即使它存在於jar的資源文件夾中,它也無法訪問該XML文件。

為什么會這樣呢? 怎么做?

我通過這種方式訪問​​XML文件:

private void initializeDocument()
{

    try {
        docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilder = docBuilderFactory.newDocumentBuilder();
        /*  
        URL xmlResource = getClass().getResource("/server.xml");
        File xmlFile = new File(xmlResource.getPath());
         */
        //
        document = docBuilder.parse (new File("ServerResources/server.xml"));
    } catch (ParserConfigurationException e) {

        e.printStackTrace();
    } catch (SAXException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }



}

您的問題是這一行:

File xmlFile = new File(xmlResource.getPath());

JAR中的資源不是文件

相反,您必須使用getClass().getResourceAsStream()並在該流中使用DocumentBuilder

試試這個代碼片段...

讓我知道它是否有效...

String fileURI = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
    fileURI = fileURI.substring(0, fileURI.length()-4);
    fileURI = fileURI+"ServerResources/server.xml";
    String actualFileURI= URLDecoder.decode(fileURI);

    document = docBuilder.parse (new File(actualFileURI));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM