Java 访问另一个类中的config.properties文件
我在resources文件夹中的config.properties文件中有一个特定于环境的属性列表。然后我有一个单独的类GetDatabase.java,我想从配置文件中获取值。文件结构如下Java 访问另一个类中的config.properties文件,java,properties,Java,Properties,我在resources文件夹中的config.properties文件中有一个特定于环境的属性列表。然后我有一个单独的类GetDatabase.java,我想从配置文件中获取值。文件结构如下 ├───main │ ├───java │ └───resources │ └───test ├───java │ ├───Database │ GetDatabase.java │ └───Resources │
├───main
│ ├───java
│ └───resources
│
└───test
├───java
│ ├───Database
│ GetDatabase.java
│
└───Resources
│
├───resources
config.properties
我的配置文件条目如下所示:
dev1URL=https://mos-dev.1.com
dev2URL=https://mos-dev.2.com
dev3URL=https://mos-dev.3.com
在我的GetDatabase类中,我使用getProperty方法编写了一些代码来调用属性文件,但它返回为null。我是不是遗漏了什么
下面是GetDatabase类:
package Database;
import java.sql.*;
import java.util.Properties;
public class GetDatabase {
{
final ClassLoader loader = getClass().getClassLoader();
try {
try (InputStream config = loader.getResourceAsStream("config.properties")) {
properties.load(config);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public ResultSet runQuery(String strQuery) throws SQLException {
String driver = properties.getProperty("dev1URL");
System.out.println("db driver string is here " + driver);
您是否尝试过类路径文件,如:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class App {
public static void main( String[] args ){
Properties prop = new Properties();
InputStream input = null;
try {
String filename = "config.properties";
input = App.class.getClassLoader().getResourceAsStream(filename);
if(input==null){
System.out.println("Sorry, unable to find " + filename);
return;
}
//load a properties file from class path, inside static method
prop.load(input);
//get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
} finally{
if(input!=null){
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
来源:您可以在实例初始值设定项块中加载属性:
您不加载config.properties…同时返回结果集的错误率为99.99%design@Lino谢谢可能需要调查一下。但它现在似乎有效,所以我不得不改天再讨论这个问题。这是另一个话题。我想知道我是不是太简单了。我需要创建另一个类来读取配置文件并从我的GetDatabase调用这个类吗?我想你可以简单地在你的GetDatabase类中加载config.properties。它应该是InputStream而不是InputStream吗?@Matt yes exaclty在我的手机上写道:)我不得不稍微更改建议的代码。但它现在在properties.load(config)行失败;我将用GetDatabase类的外观更新原始代码now@Matt不需要两次写一个try-catch,我已经更新了我的答案。还有,你能告诉我什么不起作用吗?干杯。我更新了代码。我得到了java.lang.NullPointerException的一个错误:inStream参数为null,并且它似乎在properties.load(config)行失败;
public class GetDatabase {
private final Properties properties = new Properties();
{
final ClassLoader loader = getClass().getClassLoader();
try(InputStream config = loader.getResourceAsStream("config.properties")){
properties.load(config);
} catch(IOException e){
throw new IOError(e);
}
}
// The rest of your code
}