当同一个jar文件放在其他项目中时,允许jar文件访问其中的文件夹

时间:2014-03-04 08:13:46

标签: java jar configuration-files

我创建了一个应用程序来完成一些工作,它里面有一个配置文件夹(名为/xml/Configuration.xml)。现在,我试图在多个项目中使用相同的jar并且我想要的唯一更改通过更改jar文件中包含的配置文件来实现它。

String xmlConfigPath = System.getProperty(user.dir) + File.separator
                + "xml" + File.separator + "Configuration.xml";

正如您在此处所看到的,我使用“user.dir”后跟完整的文件名来访问XML文件。当项目中添加的jar从其他用户运行时,这个(用户目录)显然会发生变化.dir因此找不到添加到我的项目中的jar文件中的Configuration.xml文件。

有没有办法让这个jar访问自己的配置文件夹,而不管它放在哪个项目或位置?

请参阅以下代码 在我的jar文件中,我有以下函数加载配置

/**
     * This method is responsible for reading the EMail Configuration
     * @return <MailSender>
     * @throws Exception 
     */
    private static MailSender getConfig(String configPackagePath, String fileName) throws Exception  {
        JAXBContext jaxbContext;
        Unmarshaller unmarshaller;
        StreamSource source;
        JAXBElement<MailSender> mailSenderElement;
        MailSender mailSenderConfig = null;
        String xmlConfigPath = getUserDirectoryPath() + File.separator
                + ApplicationConstants.XML + File.separator + fileName;
        try {
            jaxbContext = JAXBContext.newInstance(configPackagePath);
            File file = new File(xmlConfigPath);
            unmarshaller = jaxbContext.createUnmarshaller();
            source = new StreamSource(file);
            mailSenderElement = unmarshaller.unmarshal(source, MailSender.class);
            mailSenderConfig = mailSenderElement.getValue();
        } catch (JAXBException e) {
            String errorMessage = "Error encountered while reading the EMail XML Configuration file at " + xmlConfigPath;
            throw new Exception(errorMessage, e);
        }
        return mailSenderConfig;
    }

    /**
     * This method is responsible for fetching the User Directory Path
     * @return <String> userDirectoryPath
     */
    private static String getUserDirectoryPath() {
        return System.getProperty(ApplicationConstants.USER_DIR);
    }

现在,当它作为独立项目运行时,它找到正确的路径并且工作正常。现在,当我将它打包为jar时,这会失败,因为它无法从当前用户目录中获取文件。这里的意图是我希望jar文件使用绝对路径来访问已放在其中的文件,而不必与它(jar文件)本身放置位置有任何关系。

3 个答案:

答案 0 :(得分:0)

您应该将配置文件放在应用程序的classpath上,然后使用ClassLoader.getResourceAsStream

加载它

这意味着例如在Eclipse中使用xml/作为源文件夹,然后您可以使用以下命令从任何地方获取配置文件:

getClass().getResourceAsStream("/xml/Configuration.xml");

答案 1 :(得分:0)

一些建议:

答案 2 :(得分:0)

如果文件在JAR文件中,那么您应该使用类似:

File conf=new File(getClass().getResource("/xml/Configuration.xml").toURI());
// The "absolute path" here points at the root of the JAR