0

用下面的代码解决了这个问题——不是最优雅的方式——但我需要一个快速解决这个任务的方法

package six.desktop.gui.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class Config
{
    private static final String configFileName = "/config/config.ini";

    private Config()
    {

    }

    public static String getPropertyValue(String propertyName) throws IOException
    {
        URL url = new Config().getClass().getResource(configFileName);


        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));

        String inputline = "";
        while ((inputline = br.readLine()) != null)
        {
           if (inputline.contains(propertyName))
           {
               int index = inputline.indexOf(propertyName);
               index += propertyName.length() + 1;

               return inputline.substring(index, inputline.length());
           }
        }
        return null;
    }
}

我希望能够配置包含与 jar 位于同一级别的数据库连接字符串的文件。我怎么能做到这一点?还是我想要的有不同的方法?

我有一个 DB 处理程序类,目前它刚刚硬编码了连接。

4

3 回答 3

4

如果“与 JAR 相同级别”是指属性文件与 JAR 文件位于同一目录中,那么完成您正在尝试的操作的极其简单的方法是:

public class MyMain {
   Properties props;
   MyMain(Properties props) {
      this.props = props;
   }

   public static void main(String[] args)
      throws Exception
   {
      File f = new File("just_the_name.properties");
      FileInputStream fis = new FileInputStream(f);
      Properties props = new Properties();
      props.load(fis);
      // Now, you'll have your properties loaded from "just_the_name.properties"
      MyMain mm = new MyMain(props);
      // ... and do whatever you need to do ... 
   }

我还建议您使用一个包含存储在各个类成员中的所有属性的类,以便您轻松使用它们。

如果您的属性文件位于JAR文件中,您可以按照之前的帖子建议进行操作。

希望能帮助到你。

于 2009-03-15T21:58:00.257 回答
4

这段代码是你的开始......

private static URI getJarURI()
    throws URISyntaxException
{
    final ProtectionDomain domain;
    final CodeSource       source;
    final URL              url;
    final URI              uri;

    domain = Main.class.getProtectionDomain();
    source = domain.getCodeSource();
    url    = source.getLocation();
    uri    = url.toURI();

    return (uri);
}

这将获取您正在运行的 Jar 文件的 URI。

于 2009-03-15T21:35:43.400 回答
1

我可以立即想到三个选项。首先是找出 jar 文件的名称,这可以通过对调用返回的 URL 进行一些棘手的检查来完成Class.getResource(),然后计算出完全限定的配置文件名。

第二种选择是将目录本身放在类路径中,并以InputStreamusingClass.getResourceAsStream()或的形式请求资源ClassLoader.getResourceAsStream()

最后,您可以通过其他方式(例如通过系统属性)传入配置文件的名称,并基于此加载文件。

就我个人而言,我喜欢第二个选项——除此之外,这意味着你可以在以后将配置文件发送jar 中,如果你愿意的话——或者将配置文件移动到另一个目录并只更改类路径。如果您将配置文件名直接指定为系统属性,后者也很容易:这将是我的第二选择。

于 2009-03-15T21:14:42.060 回答