修复了以下代码的问题 - 不是最优雅的方式 - 但我需要快速解决此作业
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处理程序类,目前只有硬连接的连接。
答案 0 :(得分: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。
答案 1 :(得分: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文件中,你可以像之前的帖子那样建议。
希望它有所帮助。
答案 2 :(得分:1)
我可以立即想到三个选项。第一个是找出jar文件的名称,这可以通过调用Class.getResource()
调用返回的URL进行一些棘手的检查来完成,然后计算出完全限定的配置文件名。
第二个选项是将目录本身放在类路径中,并使用InputStream
或Class.getResourceAsStream()
要求资源为ClassLoader.getResourceAsStream()
。
最后,您可以通过其他方式传递配置文件的名称,例如通过系统属性,并根据该文件加载文件。
就我个人而言,我喜欢第二个选项 - 除了其他任何选项之外,它意味着您可以在以后的日期在罐中发送配置文件,如果您想 - 或移动配置文件到另一个目录,只需更改类路径。如果您直接将配置文件名指定为系统属性,后者也会很容易:这将是我的第二选择。