2017-06-09 4 views
1

リソースフォルダにあるファイルを読み取ることができないアプリケーション用の実行可能なjarを作成すると問題が発生します。 リソースファイルは、src> main> resourcesの下にあります。classLoader.getResource()はEclipseで動作しますが、デプロイ時にnullを返します

.xml設定ファイルとそこにlog4j.propertiesファイルがあります。

私はEclipse内からアプリケーションを実行するとすべて正常に動作します(xmlが読み込まれ、ログファイルが作成されます)が、実行可能なjarとして展開すると、突然ログファイルがもう書き込まれなくなり、classLoader.getResource(xmlFile) nullを返します。

これを解決する方法はありますか?

これは私が使用したコードの一部です:パラメータXMLFILEのようなファイル名だけで 「readMe.xml」

private Document xmlDocument (String xmlFile) throws ParserConfigurationException, SAXException, IOException{ 
    // return null if the file is not an xml file 
    System.out.println(" - xmlFile : " + xmlFile); 
    if(! xmlFile.substring(xmlFile.lastIndexOf(".") + 1).toLowerCase().equals("xml") ){ 
     return null; 
    } 

    //Get Document Builder 
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = factory.newDocumentBuilder(); 

    //Build Document 
    ClassLoader classLoader = getClass().getClassLoader(); 

    URL res = classLoader.getResource(xmlFile); 
    System.out.println(" - res : " + res); 

    File file = new File(classLoader.getResource( xmlFile).getFile()); 
    if (file == null){ 
     System.out.println(" - xmlDocument - OUT"); 
     return null; 
    } 

    Document document = builder.parse(new File(classLoader.getResource(xmlFile).getFile())); 
    //Normalise the XML Structure; 
    System.out.println(" - xmlDocument 5 - before normalizing document"); 
    document.getDocumentElement().normalize(); 

    return document; 
} 
+1

では、すべてが瓶になりましたか? jarファイル内のオブジェクトはファイルではなく、 'File'を使ってそれらにアクセスすることはできません。 'getResourceAsStream'を見てください。 –

+0

.jarファイルに 'readMe.xml'エントリが含まれていることを確認しましたか?あなたのIDEで.jarファイルの内容を調べるか、すべてのJDKに付属する 'jar'ツールを使うか、コピーを作成してそのコピーの拡張子を' .zip'に変更してから、任意のzipツールを使用してファイルを調べます(すべての.jarファイルは実際にはzipファイルなので)。 URL.getFile()**はURLを有効なファイル名に変換しません**。 URLをファイルに変換しないでください。 'try(InputStream file = classLoader.getResourceAsStream(xmlFile)){document = builder.parse(file);}を使用します。 } '代わりに。 – VGR

答えて

0

あなたはクラスパス内のリソースを指定する必要があり、これを試してみてください。

  1. 実行可能なjarではなく、通常のjarとしてクラスをエクスポートします。
  2. すべてのリソースを設定ディレクトリ<base_paths>/configに、jarsをディレクトリ<base_paths>/libにコピーします。
  3. ファイル名を指定して実行コマンドウィンドウで

java -cp <base_paths>/config;<base_paths>/lib/yourJar.jar com.xyz.YourMainclass 

のUnix

java -cp <base_paths>/config:<base_paths>/lib/yourJar.jar com.xyz.YourMainclass 
関連する問題